簡體   English   中英

(在Boost :: Python中)如何實例化python模塊中定義的類的對象並從C ++調用其方法

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

假設我在python模塊中定義了一個類:

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

我想使用boost :: python實例化該類的對象。 我通過以下方式嘗試了它:

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")()

它會打印init然后崩潰。 我觀察到執行后

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

打印帶有的字符串表示形式

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

不打印。 所以出了點問題。 我該怎么做對?

我自己找到了答案:使用eval代替exec。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM