且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Boost Python:在函数中通过引用传递变量时出错

更新时间:2021-08-16 05:47:18

正如 kindall 所述,python字符串是不可变的.一种解决方案可以是stl :: string包装器.您的python端会受到影响,但这是一个简单的解决方案,并且需要为该接口支付少量费用

As kindall mentioned, python strings are immutable. one solution can be a stl::string wrapper. your python side will be affected, but it's a sipmle solution and a small price to pay for that interface

class_<std::string>("StlString")
        .def(init<std::string>())
        .def_readonly("data", &std::string::data);

请注意,将 assign 运算符python转换为c ++ stl将由boost提供,但是您必须公开 data 成员才能访问存储的数据.我为c ++对象的外观添加了另一个构造函数.

note that the assign operator, python to c++ stl will be given by boost, but you'll have to expose the data member in order to access the stored data. Iv'e added another costructor for the look and feel of c++ object.

>>> import test
>>> stlstr = test.StlString()
>>> stlstr
<test.StlString object at 0x7f1f0cda74c8>
>>> stlstr.data
''
>>> stlstr = 'John'
>>> stlstr.data
'John'
>>> initstr = test.StlString('John')
>>> initstr.data
'John'