【问题标题】:Boost Python: Error when passing variable by reference in a functionBoost Python:在函数中通过引用传递变量时出错
【发布时间】:2017-11-14 22:27:20
【问题描述】:

我想了解为什么以下函数在python中不起作用:

#include<boost/python.hpp>
#include<iostream>
#include<string>

void hello(std::string& s) {

   std::cout << s << std::endl;
}

BOOST_PYTHON_MODULE(test)
{
   boost::python::def("hello", hello);
}

当我将库导入 python 时

import test
test.hello('John')

我得到一个错误:

test.hello(str)
did not match C++ signature:
   hello(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > {lvalue})

一切都只适用于'std::string s',但我想通过引用而不复制它来引用对象。我注意到任何其他带有引用的函数都会弹出错误,例如整数&。

【问题讨论】:

  • 如果一种方式有效,而另一种方式给你一个错误信息,那通常意味着你应该以第一种方式做事。
  • 字符串来自 Python。如果你得到它的引用,你可以修改它。但是字符串在 Python 中是不可变的。所以你不能这样做。

标签: python c++ boost-python


【解决方案1】:

正如kindall 提到的,python 字符串是不可变的。一种解决方案可以是 stl::string 包装器。你的 python 端会受到影响,但它是一个简单的解决方案,并且为该接口付出的代价很小

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

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

>>> 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多