Calling Python functions from C++

后端 未结 4 1174
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 16:53

I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using

相关标签:
4条回答
  • 2020-12-09 17:15

    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.

    0 讨论(0)
  • 2020-12-09 17:16

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

    0 讨论(0)
  • 2020-12-09 17:30

    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.

    0 讨论(0)
  • 2020-12-09 17:34

    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()
    
    0 讨论(0)
提交回复
热议问题