在C语言中调用Python代码可以通过以下几种方法实现:
方法一:直接嵌入Python解释器
初始化Python解释器:
使用`Py_Initialize()`函数初始化Python解释器。
运行Python代码:
可以使用`PyRun_SimpleString()`函数直接运行单行Python代码,或使用`PyRun_File()`函数运行一个Python脚本文件。
结束解释器:
使用`Py_Finalize()`函数结束Python解释器。
示例代码:
```c
include
int main() {
Py_Initialize();
PyRun_SimpleString("print('Hello, world!')");
Py_Finalize();
return 0;
}
```
方法二:使用Python C扩展库
创建共享库:
在C代码中实现Python函数,并编译生成一个共享库(如`.so`文件或`.pyd`文件)。
加载共享库:
在C代码中使用`dlopen()`(Linux)或`LoadLibrary()`(Windows)加载共享库。
调用Python函数:
通过共享库中的函数指针调用Python函数。
示例代码:
```c
// shared_lib.c
include
static PyObject* hello_world(PyObject* self, PyObject* args) {
const char* msg;
if (!PyArg_ParseTuple(args, "s", &msg))
return NULL;
printf("%s\n", msg);
Py_RETURN_NONE;
}
static PyMethodDef MyMethods[] = {
{"hello_world", hello_world, METH_VARARGS, "Print a message."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef mymodule = {
PyModuleDef_HEAD_INIT,
"mymodule",
NULL,
-1,
MyMethods
};
PyMODINIT_FUNC PyInit_mymodule(void) {
return PyModule_Create(&mymodule);
}
```
编译共享库:
```sh
gcc -shared -fPIC -o libmymodule.so shared_lib.c -I/usr/include/python3.8
```
在C代码中加载并调用:
```c
include include int main() { void* handle; handle = dlopen("./libmymodule.so", RTLD_NOW); if (!handle) { fprintf(stderr, "Cannot load shared library\n"); return 1; } typedef PyObject* (*hello_world_t)(); hello_world_t hello_world = (hello_world_t)dlsym(handle, "hello_world"); if (!hello_world) { fprintf(stderr, "Cannot find function 'hello_world'\n"); dlclose(handle); return 1; } PyObject* result = hello_world(); Py_DECREF(result); dlclose(handle); return 0; } ``` 方法三:使用系统命令 使用`system()`函数执行Python脚本。 示例代码: ```c include int main() { system("python your_python_program.py"); return 0; } ``` 方法四:使用ctypes库 将C代码编译为动态库(如`.so`文件)。 使用`ctypes`库加载动态库并调用其中的函数。 示例代码: ```c // func.c include int func(int a) { return a * a; } ``` 编译动态库: ```sh gcc -shared -fPIC -o libfunc.so func.c ``` 在Python中加载并调用: ```python import ctypes 加载动态库 lib = ctypes.CDLL('./libfunc.so') 定义函数原型 lib.func.argtypes = [ctypes.c_int] lib.func.restype = ctypes.c_int 调用函数 result = lib.func(99) print(result) ``` 总结 以上方法执行Python脚本:
编译C代码为动态库:
在Python中加载动态库: