我正在尝试将一个简单的(测试)Python 脚本嵌入到 C++ 中。请参阅此问题以供参考:Undefined reference to `main` error when embedding Python in C++我正在尝试在 C++ 中嵌入 Python。这是我的 Python 文件(名称为 EmbedTest.py):
from __future__ import division
class model:
def init(self,a,b):
self.a = a
self.b = b
def test_method(a,b):
m = model(a,b)
m.add(1)
print("a: ",a,"b: ",b)
return (a+b,a-b,a*b)
这是我的 C++ 文件(名称为 EmbedTest.cpp,与 EmbedTest.py 位于同一文件夹中)
#include <Python.h>
int main(int argc, char *argv[]) {
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue, *pValue_1, *pValue_2;
double sum,diff,prod;
double a = atof(argv[1]);
double b = atof(argv[2]);
Py_Initialize();
pName = PyUnicode_DecodeFSDefault("EmbedTest.py");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if(pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule,"test_method");
if(pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(2);
pValue_1 = PyFloat_FromDouble(a);
pValue_2 = PyFloat_FromDouble(b);
if (!pValue_1) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
if (!pValue_2) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
PyTuple_SetItem(pArgs, 0, pValue_1);
PyTuple_SetItem(pArgs, 1, pValue_2);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
sum = PyFloat_AsDouble(PyTuple_GetItem(pValue,0));
diff = PyFloat_AsDouble(PyTuple_GetItem(pValue,1));
prod = PyFloat_AsDouble(PyTuple_GetItem(pValue,2));
printf("a: %f b: %f sum: %f diff: %f prod: %f",a,b,sum,diff,prod);
Py_DECREF(pValue);
}
牛魔王的故事
繁星coding
相关分类