简体   繁体   中英

Using std::string as return type in Boost.python exported function

I have a very simple example of a C++ function that I export to python (2.7.13) via Boost.Python. Code below:

#include <string>

#include <boost/python.hpp>

const char* greet()
{
    return "hello, world!";
}

BOOST_PYTHON_MODULE(libhello)
{
    using namespace boost::python;
    def("hello_world", greet);
}

I compile on a OSX 10.10.5 machine with

g++ -I ~/boost -L ~/boost/stage/lib\
-L /System/Library/Frameworks/Python.framework/Versions/Current\
-fpic export.cpp -shared -lboost_python -lPython -olibhello.so

It correctly produces the libhello.so which I can then use in python

import libhello as lh
lh.hello_world() # correctly returns the string "hello, world"

However, when I change the return type of greet in the C++ file to std::string , ie

std::string greet(){...}

I am getting the following crash in python after running lh.hello_world() :

Fatal Python error: PyEval_SaveThread: NULL tstate
Abort trap: 6

and pyhton crashes. Any idea why? Does it have to do with the non-POD return type?

The issue seemed to be related to the libpython the linker used by default, which was the OSX original one located within /System/Library/Frameworks/Python.framework . When I linked agains libpython from my installation of python located within Library/Frameworks/Python.framework , everything worked fine. The whole command line I used is posted below, in case someone bumps into this in the future:

g++ -I /Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/\
 -I $HOME/boost -fpic export.cpp -shared -lboost_python -lpython2.7 -olibhello.so\
 -L /Library/Frameworks/Python.framework/Versions/2.7/lib\
 -L $HOME/boost/stage/lib

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM