dzh*_*lil 49 c c++ python python-embedding python-c-api
我想调用一个在C语言的python模块中定义的自定义函数.我有一些初步代码可以做到这一点,但它只是将输出打印到stdout.
mytest.py
import math
def myabs(x):
return math.fabs(x)
Run Code Online (Sandbox Code Playgroud)
TEST.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;
}
Run Code Online (Sandbox Code Playgroud)
如何将返回值提取到C double并在C中使用它?
ThR*_*R37 68
如前所述,使用PyRun_SimpleString似乎是一个坏主意.
您绝对应该使用C-API提供的方法(http://docs.python.org/c-api/).
阅读介绍是了解其工作方式的第一步.
首先,您必须了解PyObject,它是C API的基本对象.它可以表示任何类型的python基本类型(string,float,int,...).
存在许多函数来将例如python字符串转换为char*或将PyFloat转换为double.
首先,导入您的模块:
PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);
Run Code Online (Sandbox Code Playgroud)
然后获取对您的函数的引用:
PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));
Run Code Online (Sandbox Code Playgroud)
然后得到你的结果:
PyObject* myResult = PyObject_CallObject(myFunction, args)
Run Code Online (Sandbox Code Playgroud)
并回到双重:
double result = PyFloat_AsDouble(myResult);
Run Code Online (Sandbox Code Playgroud)
您应该明确检查错误(参见Mark Tolonen给出的链接).
如果您有任何疑问,请不要犹豫.祝好运.
kil*_*les 20
下面是我编写的示例代码(在各种在线资源的帮助下)将字符串发送到Python代码,然后返回一个值.
这是C代码call_function.c
:
#include <Python.h>
#include <stdlib.h>
int main()
{
// Set PYTHONPATH TO working directory
setenv("PYTHONPATH",".",1);
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;
// Initialize the Python Interpreter
Py_Initialize();
// Build the name object
pName = PyString_FromString((char*)"arbName");
// Load the module object
pModule = PyImport_Import(pName);
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");
if (PyCallable_Check(pFunc))
{
pValue=Py_BuildValue("(z)",(char*)"something");
PyErr_Print();
printf("Let's give this a shot!\n");
presult=PyObject_CallObject(pFunc,pValue);
PyErr_Print();
} else
{
PyErr_Print();
}
printf("Result is %d\n",PyInt_AsLong(presult));
Py_DECREF(pValue);
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
// Finish the Python Interpreter
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是Python代码,在文件中arbName.py
:
def someFunction(text):
print 'You passed this Python program '+text+' from C! Congratulations!'
return 12345
Run Code Online (Sandbox Code Playgroud)
我使用该命令gcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.out
来运行此过程.我在redhat上.我建议使用PyErr_Print(); 用于错误检查.
调用Python函数并检索结果的完整示例位于http://docs.python.org/release/2.6.5/extending/embedding.html#pure-embedding:
#include <Python.h>
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(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 = PyInt_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
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\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为了防止像其他答案中那样出现额外的 .py 文件,您可以只检索__main__
由第一次调用创建的模块PyRun_SimpleString
:
PyObject *moduleMainString = PyString_FromString("__main__");
PyObject *moduleMain = PyImport_Import(moduleMainString);
PyRun_SimpleString(
"def mul(a, b): \n"\
" return a * b \n"\
);
PyObject *func = PyObject_GetAttrString(moduleMain, "mul");
PyObject *args = PyTuple_Pack(2, PyFloat_FromDouble(3.0), PyFloat_FromDouble(4.0));
PyObject *result = PyObject_CallObject(func, args);
printf("mul(3,4): %.2f\n", PyFloat_AsDouble(result)); // 12
Run Code Online (Sandbox Code Playgroud)