c++ - Python C API 和 C++ 函数

标签 c++ python python-3.x python-c-api

我正在尝试在我的 C++ 程序中扩展 Python 解释器,我的问题如下。
当我尝试调用一个函数时,如以下代码中所述,我得到一个 NameError , 来自 Python 解释器。 错误是

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

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

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");

然而,我不断收到错误。有人可以解释一下,我在这里做错了什么吗?

最佳答案

PyRun_SimpleString("import test\n"
                   "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。

关于c++ - Python C API 和 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755788/

相关文章:

c++编码选择开关代码上的每个案例

C++继承+重载

python - 如何用pyscard写智能卡

python - 'module' 的实例没有 'LBPHFaceRecognizer_create' 成员

python - 路易吉流水线 : No module named pwd in Windows

c++ - 使用 Qt 和 pjsip 在一个应用程序中的多个端口上监听 SIP

c++ - 我在标准库中遇到编译错误。这是怎么回事?

python - 在 python setup.py install_requires 列表中传递参数

python - 如何避免 Pillow 在保存图像后稍微编辑我的图像?

python - 调试 LDAP 库/连接 Wireshark/或其他