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

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

所以,StackOverflow,我被难住了。

我拥有的代码是带有嵌入式 Python 的 C++ 函数。我在 C++ 端生成一条消息,将其发送到 python,然后返回一条不同的消息。我让它工作了,我测试了它,到目前为止,一切都很好。

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

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 方面,我有以下接收器代码:

import turkey

我得到以下响应:

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 端对其进行初始化的文档。我意识到我可能只是错过了一个微不足道的步骤,但我终生无法弄清楚它是什么。谁能帮忙?

最佳答案

最终,答案是我缺少的一个功能。在调用 Py_Initialize 之前包含在初始化函数的开头:

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

Python 文档没有提到 PyImport_AppendInittab,只是顺便提一下,这就是为什么我在跳转时遇到了如此困难的时间。

对于将来发现此问题的任何其他人:您不需要创建 DLL 来扩展 python 或使用预构建的库将模块引入 Python。它可以比这容易得多。

关于python - 嵌入式 python 如何调用 C++ 类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49182978/

相关文章:

python - Django 中的自定义标记

python - Django CMS 支持分类法或标签吗?

c++ - 条件随机场 (CRF) 实现/库

Python Pandas 过滤;类型错误 : cannot convert the series to <class 'int' >

Python3 : inheriting from list breaks automagically provided __ne__ when __eq__ is defined?

python - 在 Python 中打开文件会返回一个流吗?

python - 您可以使用流而不是本地文件上传到 S3 吗?

python - Django,我的 TabularInline 中有许多重复的查询

java - 使用 JNA 从 java 中的内部源对象 (.so) 文件调用 C++ 函数时出现链接异常。

c++ - 在 C++ 中的 3D map 中插入值