Boost Python: Error when passing variable by reference in a function

痞子三分冷 提交于 2019-12-13 02:44:24

问题


I would like to understand why the following function does not work in 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);
}

When I import library into python

import test
test.hello('John')

I get an error:

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

Everything works with just 'std::string s', but I would like to the object by reference without copying it. I noticed that the error pops up for any other function with references like e.g. int&.


回答1:


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);

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'


来源:https://stackoverflow.com/questions/47296287/boost-python-error-when-passing-variable-by-reference-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!