开发者

(in Boost::Python)How can I instantiate an object of a class defined in a python module and invoke its methods from C++

Assume I have a class defined in a python module:

class A(object):
    def __init__(self):
        print 'init'
    def method(self):
        print 'method'

I'd like to instantiate an object of that class with boost::python. I tried it the following way:

namespace py = boost::python;

// importing the module and extracting its namespace to
// the variable `ns`
...

py::object a = py::exec("A()", ns)
a.attr("method")()

which prints init and then crashes. I observed that after executing

py::object a = py::exec("A()", ns)

printing the stri开发者_运维技巧ng representation of a with

std::cout << std::string(py::extract<std::string>(py::str(a))) << std::endl;

prints None. So something went wrong. How do I do this right?


I found the answer myself: use eval instead of exec.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜