pythoncapi和C++;功能 我试图在我的C++程序中扩展Python解释器,我的问题如下。 当我试图调用一个函数时(在下面的代码中解释),我从Python解释器中得到一个namererror。 错误是
pythoncapi和C++;功能 我试图在我的C++程序中扩展Python解释器,我的问题如下。 当我试图调用一个函数时(在下面的代码中解释),我从Python解释器中得到一个namererror。 错误是,c++,python,python-3.x,python-c-api,C++,Python,Python 3.x,Python C Api,回溯(最近一次呼叫最后一次): 文件“”,第3行,在模块中 名称错误:未定义名称“func” 根据我在这里使用的PythonWiki版本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;
回溯(最近一次呼叫最后一次):
文件“”,第3行,在模块中
名称错误:未定义名称“func”
根据我在这里使用的PythonWiki版本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\u AppendInittab(“test”,PyInit\u test)代码>
Py_Initialize()代码>,然后我尝试运行一个简单的测试,使用
PyRun_SimpleString("import test\n"
"print('Hi!')\n"
"b = func(5)\n"
"print(b)\n");
然而,我一直在犯错误。谁能解释一下,我做错了什么
PyRun_SimpleString("import test\n"
"print('Hi!')\n"
"b = test.func(5)\n" # <--
"print(b)\n");
请注意,如果您还不熟悉如何编写CPython C扩展模块,我建议您使用CFFI。我同意Armin Rigo的所有修复,并添加此修复:
PyImport\u AppendInittab(“test”和&PyInit\u test)代码>
将函数的地址传递给PyImport\u AppendInittab
int command; // not "int *"
double sts;
if( !PyArg_ParseTuple(args, "i", &command) )