在Boost.python导出函数中使用std :: string作为返回类型 [英] Using std::string as return type in Boost.python exported function

查看:62
本文介绍了在Boost.python导出函数中使用std :: string作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的C ++函数示例,该示例通过Boost.Python导出到python(2.7.13).下面的代码:

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

我在

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

它会正确生成 libhello.so ,然后可以在python中使用

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"

但是,当我将C ++文件中的 greet 的返回类型更改为 std :: string 时,即

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

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

运行 lh.hello_world()后,我在python中遇到以下崩溃:

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

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

,pyhton崩溃.知道为什么吗?与非POD返回类型有关吗?

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

推荐答案

此问题似乎与默认使用的链接器 libpython 有关,链接器是位于内的OSX原始链接器./System/Library/Frameworks/Python.framework .当我从位于 Library/Frameworks/Python.framework 内的 python 安装中再次链接了 libpython 时,一切正常.我使用的整个命令行发布在下面,以防将来有人碰到它:

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

这篇关于在Boost.python导出函数中使用std :: string作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆