嵌入式Python如何调用C++类的函数?

2024-04-25 17:56:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,StackOverflow,我被难住了。在

代码,我有一个带有嵌入Python的C++函数。我在C++端生成一个消息,将其发送到Python,得到不同的消息。我成功了,我测试过了,到目前为止,一切都很好。在

下一步是我需要Python自己生成消息并将它们发送到C++。这就是我开始陷入困境的地方。在花了几个小时对文档费解之后,似乎最好的方法是定义一个模块来保存我的函数。所以我写了以下存根:

static PyMethodDef mailbox_methods[] = {
    { "send_external_message", 
      [](PyObject *caller, PyObject *args) -> PyObject *
      {
         classname *interface = (classname *) 
             PyCapsule_GetPointer(PyTuple_GetItem(args, 0), "turkey");
         class_field_type toReturn;
         toReturn = class_field_type.python2cpp(PyTuple_GetItem(args, 1));
         interface ->send_message(toReturn);
         Py_INCREF(Py_None);
         return Py_None;
     },
     METH_VARARGS, 
     "documentation" },
     { NULL, NULL, 0, NULL }
};

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "turkey",
    "documentation",
    -1,
    mailbox_methods
};

//defined in header file, just noting its existence here
PyObject *Module;

PyMODINIT_FUNC PyInit_turkey()
{
    Module = PyModule_Create(&moduledef);
    return Module;
}

在Python方面,我有以下接收器代码:

^{pr2}$

我得到以下答复:

ImportError: No module named 'turkey'

我现在很困惑。下面是我的初始化函数中的代码:

PyInit_turkey();
PyObject *interface = PyCapsule_New(this, "instance", NULL);
char *repr = PyUnicode_AsUTF8(PyObject_Repr(Module));
cout << "REPR: " << repr << "\n";
if (PyErr_Occurred())
    PyErr_Print();

打印出来了

REPR: <module 'turkey'>
Traceback (most recent call last):
    <snipped>
    import turkey
ImportError: No module named 'turkey'

因此模块存在于,但它永远不会传递给Python。我找不到关于如何传入并在Python端初始化它的文档。我意识到我可能只是错过了一个微不足道的步骤,但我一辈子都搞不清这是什么。有人能帮忙吗?在


Tags: 模块函数代码文档py消息argsstatic
1条回答
网友
1楼 · 发布于 2024-04-25 17:56:03

最后,答案是,我遗漏了一个功能。在我的初始化函数开始时,在我调用Py_Initialize之前:

PyImport_AppendInittab("facade", initfunc);
Py_Initialize();
PyEval_InitThreads();

Python文档没有提到PyImport_AppendInittab,除非在传递过程中,这就是为什么我在跳转时遇到了如此困难的原因。在

对于将来发现这一点的人:您不需要创建DLL来扩展python,也不需要使用预构建的库将模块引入python。这比那容易得多。在

相关问题 更多 >

    热门问题