Calling Python functions from C++

♀尐吖头ヾ 提交于 2019-11-28 09:04:36
Matthew Scouten

If it might have any name:

Pass it to a function that takes a boost::python::object.

bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
      pycb = cb;
}

If it is in a single known namespace with a consistent name:

bp::object pycb = bp::scope("namespace").attr("callback");

bp::object has operator() defined, so you call it just like any function

ret = pycb()

Not a clue. But you can use PyObject_Call() to call it once you have the function object.

I've not used it before, but the reference manual has a section called Calling Python Functions and Methods which seems to show how to do this.

I used PyRun_SimpleString("myFunction()") as quick hack, as my function's name was known, took no args and lived in the __main__ namespace. Note you additionally need to get lock GIL if you are multi-threaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!