从C++(或C)调用中调用Python方法

2024-04-26 11:20:42 发布

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

我试图调用C++中的Python类中的方法。从中调用的C++方法是C++回调。

在这个方法中,当我试图调用python方法时,它给出了segmentation fault

我将python函数的一个实例保存在一个全局变量中,比如

// (pFunc is global variable of type PyObject*)
pFunc = PyDict_GetItemString(pDict, "PlxMsgWrapper");

其中PlxMsgWrapper是一个python方法,将在回调中使用。

在回调中,参数创建为

PyObject* args = PyTuple_Pack(2, PyString_FromString(header.c_str()),
                                 PyString_FromString(payload.c_str()));

当创建

PyObject * pInstance = PyObject_CallObject(pFunc, args);

在这一行,它给出了分割错误。在这之后,实际的python方法被称为

PyObject* recv_msg_func = PyObject_GetAttrString(module, (char *)"recvCallback");
args = PyTuple_Pack(1, pInstance);
PyObject_CallObject(recv_msg_func, args);

Tags: 方法argsmsgpackpyobjectfuncstrfromstring
3条回答

Python应该在运行它的目录中查找一个模块 但是,如果您认为问题在于python没有发现 您的文件中,可以将计算机上的任意目录添加到 程序中的模块搜索路径:

// Initialize the Python Interpreter
Py_Initialize();

// The following two lines to the trick:
// add path to your module to python's search paths
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"/path/to/python/module/here\")");

// Build the name object
pName = PyString_FromString("your_module");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyDict_GetItemString(pDict, "PlxMsgWrapper");

pArgs = ... 

if (PyCallable_Check(pFunc)) 
{
   PyObject_CallObject(pFunc, pArgs);
} else {
   PyErr_Print();
}

这并不能完全回答您的问题,但是您可以大大简化代码并避免使用Boost::Python时出现引用计数问题。

#include "boost/python.hpp"

using namespace boost::python;

int main()
{
  Py_Initialize();

  object pyFunPlxMsgWrapper = import("your_module").attr("PlxMsgWrapper");
  pyFunPlxMsgWrapper(2, "string", "data");
  return 0;
}
<> P>从C/C++回调调用Python函数时,有一些事情需要做。首先,在保存python函数对象时,需要使用以下命令增加引用计数:

Py_INCREF(pFunc)

否则,Python不知道您持有的是对象引用,它可能会对其进行垃圾收集,从而在您尝试从回调使用它时导致分段错误。

接下来你需要关注的是当你的C/C++回调被调用时线程正在运行。如果您从另一个非python创建的线程(即C/C++线程在套接字上接收数据)调用,那么您在调用任何Python API函数之前,必须< <强> > Python的全局解释器锁(吉尔)。否则程序的行为是未定义的。要获得GIL,你需要:

void callback() {
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();

    // Get args, etc.

    // Call your Python function object
    PyObject * pInstance = PyObject_CallObject(pFunc, args);

    // Do any other needed Python API operations

    // Release the thread. No Python API allowed beyond this point.
    PyGILState_Release(gstate);
}

此外,在扩展模块的init函数中,应执行以下操作以确保正确初始化线程:

// Make sure the GIL has been created since we need to acquire it in our
// callback to safely call into the python application.
if (! PyEval_ThreadsInitialized()) {
    PyEval_InitThreads();
}

否则,当您试图从非Python线程获取GIL时,可能会发生崩溃和奇怪的行为。

请参阅Non-Python Created Threads了解有关此的详细信息。

相关问题 更多 >