0

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&.

2
  • If one way works, and the other way gives you an error message, that usually means you're supposed to do things the first way. Commented Nov 14, 2017 at 22:32
  • 2
    The string is coming from Python. If you got a reference to it, you could modify it. But strings are immutable in Python. So you can't do that. Commented Nov 14, 2017 at 22:33

1 Answer 1

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 simple 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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.