我想从C调用一个在python模块中定义的自定义函数,我有一些初步的代码来完成这项工作,但它只是将输出输出输出到标准输出。
mytest.py
import math
def myabs(x):
return math.fabs(x)
测试.cpp
#include <Python.h>
int main() {
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('.')");
PyRun_SimpleString("import mytest;");
PyRun_SimpleString("print mytest.myabs(2.0)");
Py_Finalize();
return 0;
}
如何将返回值提取到C double并在C中使用?
如前所述,使用PyRun_SimpleString似乎是个坏主意。
您绝对应该使用C-API(http://docs.python.org/c-api/)提供的方法。
阅读导言是理解其工作方式的第一步。
首先,您必须了解PyObject,它是C API的基本对象。它可以表示任何类型的python基本类型(string、float、int…)。
有许多函数可以将python string转换为char*或PyFloat转换为double。
首先,导入模块:
然后获取对函数的引用:
然后得到你的结果:
回到双人间:
显然,您应该检查错误(参见Mark Tolonen给出的链接)。
如果你有任何问题,不要犹豫。祝你好运。
调用Python函数并检索结果的完整示例位于http://docs.python.org/release/2.6.5/extending/embedding.html#pure-embedding:
下面是我编写的一个示例代码(在各种在线资源的帮助下)将字符串发送到Python代码,然后返回一个值。
这是C代码
call_function.c
:以下是Python代码,在文件
arbName.py
中:我使用命令
gcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.out
运行此进程。我在读红帽。我建议使用PyErr_Print();进行错误检查。相关问题 更多 >
编程相关推荐