我想在我的C++程序中擴展Python解釋器,我的問題如下。
當我試圖調用一個函數,在下面的代碼中解釋,我從Python解釋器得到一個NameError
。 錯誤是
Python C API和C++函數
Traceback (most recent call last):
File "", line 3, in module
NameError: name 'func' is not defined
我用下面的代碼綁定它,根據Python的維基3.3.2版本,我在這裏使用
double func(int a)
{
return a*a-0.5;
}
static PyObject *TestError;
static PyObject * func_test(PyObject * self, PyObject *args)
{
const int * command;
double sts;
if(!PyArg_ParseTuple(args, "i", &command))
return NULL;
sts = func(*command);
return PyFloat_FromDouble(sts);
}
static PyMethodDef TestMethods[] = {
{"func", func_test, METH_VARARGS,
"Thing."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef testmodule = {
PyModuleDef_HEAD_INIT,
"test", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
TestMethods
};
PyMODINIT_FUNC PyInit_test()
{
PyObject *m;
m = PyModule_Create(&testmodule);
if (m == NULL)
return NULL;
TestError = PyErr_NewException("test.error", NULL, NULL);
Py_INCREF(TestError);
PyModule_AddObject(m, "error", TestError);
return m;
}
這然後我打電話PyImport_AppendInittab("test", PyInit_test);
Py_Initialize();
,然後我試圖運行一個簡單的測試,與
PyRun_SimpleString("import test\n"
"print('Hi!')\n"
"b = func(5)\n"
"print(b)\n");
但是,我不斷收到錯誤。有人能解釋一下,我在這裏做錯了什麼?
這種工作,但它墜毀。想法? –