Python C API and C++ functions

Python C API and C++ functions

本文关键字:C++ functions and API Python      更新时间:2023-10-16

我正在尝试在我的C++程序中扩展Python解释器,我的问题如下。
当我尝试调用下面的代码中解释的函数时,我从 Python 解释器那里得到了一个NameError。错误是

Traceback (most recent call last):
File "", line 3, in module
NameError: name 'func' is not defined

使用以下代码来绑定它,根据我在这里
使用的 Python 3.3.2 版的 Python wiki

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 testn" "print('Hi!')n" "b = func(5)n" "print(b)n");然而,我不断收到错误。有人可以解释一下,我在这里做错了什么吗?
PyRun_SimpleString("import testn"
                   "print('Hi!')n"
                   "b = test.func(5)n"   # <--
                   "print(b)n");

编辑:另一个问题:

int command;   // not "int *"
double sts;
if( !PyArg_ParseTuple(args, "i", &command) )

请注意,如果您还不熟悉如何编写CPython C扩展模块,我建议您使用CFFI。

我同意 Armin Rigo 的所有修复程序,我会添加这个:
PyImport_AppendInittab("test", &PyInit_test);

将函数的地址传递给 PyImport_AppendInittab