Python调用接口

发布时间: 2023-11-21 13:04 阅读: 文章来源:1MUMB4705PS

要在C语言中调用Python接口,可以使用Python C API或者第三方库如Python.h。这里给出一个使用Python C API的示例:

1. 首先确保已经安装了Python开发库。在Ubuntu系统中,可以使用以下命令安装:

sudo apt-get install python3-dev

2. 创建一个名为call_python.c的C文件,并添加以下代码:

#include

int main(int argc, char *argv[])

{

PyObject *pName, *pModule, *pFunc;

PyObject *pArgs, *pValue;

int i;

if (argc < 3) {

fprintf(stderr,"Usage: call pythonfile funcname [args]

");

return 1;

}

Py_Initialize();

pName = PyUnicode_DecodeFSDefault(argv[1]);

/* Error checking of pName left out */

pModule = PyImport_Import(pName);

Py_DECREF(pName);

if (pModule != NULL) {

pFunc = PyObject_GetAttrString(pModule, argv[2]);

/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {

pArgs = PyTuple_New(argc - 3);

for (i = 0; i < argc - 3; ++i) {

pValue = PyLong_FromLong(atoi(argv[i + 3]));

if (!pValue) {

Py_DECREF(pArgs);

Py_DECREF(pModule);

fprintf(stderr, "Cannot convert argument

");

return 1;

}

/* pValue reference stolen here: */

PyTuple_SetItem(pArgs, i, pValue);

}

pValue = PyObject_CallObject(pFunc, pArgs);

Py_DECREF(pArgs);

if (pValue != NULL) {

printf("Result of call: %ld

", PyLong_AsLong(pValue));

Py_DECREF(pValue);

}

else {

Py_DECREF(pFunc);

Py_DECREF(pModule);

PyErr_Print();

fprintf(stderr,"Call failed

");

return 1;

}

}

else {

if (PyErr_Occurred())

PyErr_Print();

fprintf(stderr, "Cannot find function \"%s\"

", argv[2]);

}

Py_XDECREF(pFunc);

Py_DECREF(pModule);

}

else {

PyErr_Print();

fprintf(stderr, "Failed to load \"%s\"

", argv[1]);

return 1;

}

Py_Finalize();

return 0;

}

3. 编译并运行代码:

gcc call_python.c -o call_python -I/usr/include/python3.8 -lpython3.8

./call_python test.py add 1 2

注意:请根据实际情况修改Python版本和头文件路径。

•••展开全文