网站建设如何导入音乐,网站做提示框,小目标网站建设,做动画 的 网站本文在 C 中调用 multi.py 脚本#xff0c;并向它传入参数并执行#xff0c;然后获得返回值并在 C 中打印结果。
目录
如何在 C 中调用 python 解析器来执行 python 代码#xff08;一#xff09;#xff1f;如何在 C 中调用 python 解析器来执行 python 代码#xff0…本文在 C 中调用 multi.py 脚本并向它传入参数并执行然后获得返回值并在 C 中打印结果。
目录
如何在 C 中调用 python 解析器来执行 python 代码一如何在 C 中调用 python 解析器来执行 python 代码二如何在 C 中调用 python 解析器来执行 python 代码三
脚本 multi.py
def multiply(a,b):print(Will compute, a, times, b)c 0for i in range(0, a):c c breturn c代码 main.cpp
官网代码直接复制过来但执行总会出错
$./a.out multi multiply 1 8
ModuleNotFoundError: No module named multi
Failed to load multi发现必须在 C 中指定 python 脚本路径才行加上下面两行 PyRun_SimpleString(import sys);PyRun_SimpleString(sys.path.append(./));最终的 main.cpp 如下
#define PY_SSIZE_T_CLEAN
#include Python.hint
main(int argc, char *argv[])
{PyObject *pName, *pModule, *pFunc;PyObject *pArgs, *pValue;int i;if (argc 3) {fprintf(stderr,Usage: call pythonfile funcname [args]\n);return 1;}Py_Initialize();PyRun_SimpleString(import sys);PyRun_SimpleString(sys.path.append(./));pName PyUnicode_DecodeFSDefault(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 PyLong_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, PyLong_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;}if (Py_FinalizeEx() 0) {return 120;}return 0;
}编译
g -I/usr/include/python3.6m -I/usr/include/python3.6m -Wno-unused-result -Wsign-compare -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE2 -fexceptions -fstack-protector-strong --paramssp-buffer-size4 -grecord-gcc-switches -m64 -mtunegeneric -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE2 -fexceptions -fstack-protector-strong --paramssp-buffer-size4 -grecord-gcc-switches -m64 -mtunegeneric -D_GNU_SOURCE -fPIC -fwrapv -L/usr/lib64 -lpython3.6m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic main.cpp执行
$./a.out multi multiply 10 8
Will compute 10 times 8
Result of call: 80总结
和 python 交互最繁琐的部分应该就是参数处理本文演示了基础数据结构的输入输出。
还有几个课题留待研究
对于真实场景需要处理复杂结构的输入输出如向量、String、Number 等怎么做如何直接调用代码片段并传参而不是脚本文件