从 C 语言调用 Python 代码有两种方式:直接嵌入 Python 解释器或使用 Python C 扩展库。前者通过 Py_Initialize() 初始化解释器、PyRun_SimpleString() 运行代码和 Py_Finalize() 结束解释器来实现;后者则创建一个共享库,在该库中包含 Python 函数的 C 实现,并通过加载库和调用函数的方式实现。
如何从 C 语言调用 Python
引言
C 语言和 Python 都是广泛使用的编程语言,它们具有不同的优势和劣势。有时,在同一个项目中使用这两种语言可能是有益的。本文将指导您如何从 C 语言调用 Python 代码。
方法
有两种主要方法可以从 C 语言调用 Python 代码:
立即学习“Python免费学习笔记(深入)”;
1. 直接嵌入 Python 解释器
2. 使用 Python C 扩展库
示例代码
直接嵌入 Python 解释器
#include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString("print('Hello, world!')"); Py_Finalize(); return 0; }
使用 Python 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); }
在 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; }
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号