如何从 C 语言调用 Python
引言
C 语言和 Python 都是广泛使用的编程语言,它们具有不同的优势和劣势。有时,在同一个项目中使用这两种语言可能是有益的。本文将指导您如何从 C 语言调用 Python 代码。
方法
有两种主要方法可以从 C 语言调用 Python 代码:
立即学习“Python免费学习笔记(深入)”;
1. 直接嵌入 Python 解释器
使用Py_Initialize()初始化 Python 解释器。 使用
PyRun_SimpleString()或
PyRun_File()运行 Python 代码。 使用
Py_Finalize()结束 Python 解释器。
2. 使用 Python C 扩展库
创建一个共享库,其中包含 Python 函数的 C 实现。 在 C 代码中加载共享库并调用 Python 函数。示例代码
直接嵌入 Python 解释器
<code class="c">#include <Python.h>
int main() {
Py_Initialize();
PyRun_SimpleString("print('Hello, world!')");
Py_Finalize();
return 0;
}</code>使用 Python C 扩展库
<code class="c">#include <Python.h>
// 在扩展库中声明 Python 函数
static PyObject* hello_world(PyObject* self, PyObject* args) {
printf("Hello, world!\n");
Py_RETURN_NONE;
}
// 初始化扩展库
static PyMethodDef module_methods[] = {
{"hello_world", hello_world, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"my_extension",
NULL,
-1,
module_methods
};
PyMODINIT_FUNC PyInit_my_extension(void) {
return PyModule_Create(&module);
}</code>在 C 代码中调用扩展库
<code class="c">#include <Python.h>
int main() {
Py_Initialize();
PyObject* module = PyImport_ImportModule("my_extension");
PyObject* hello_world = PyObject_GetAttrString(module, "hello_world");
PyObject_CallObject(hello_world, NULL);
Py_Finalize();
return 0;
}</code> 