[英]Segmentation fault on execution of C++ code from Python – using Boost.Python on Mac OS
我试图用C ++写一个库,以便可以在不同平台上使用Python(尤其是jupyter笔记本)中的方法来工作。 为此,我正在使用Boost.Python。 我正在使用macOS Sierra 10.12.6在笔记本电脑上调试代码。
我能够将源代码编译成.so
库,但是遗憾的是,当我调用它们时,其方法崩溃了。
我使用以下命令序列安装了Boost和Boost.Python库:
brew install --build-from-source --with-python --fresh -vd boost
brew install boost-python
之后,我采用了以下简单的C ++代码( main.cpp
):
#include <boost/python.hpp>
using namespace boost::python;
#include <string>
namespace {
std::string greet() {
return "hello, world";
}
int square(int number) {
return number * number;
}
}
BOOST_PYTHON_MODULE(boost_python_example)
{
def("greet", greet);
def("square", square);
}
并创建了一个CMakeLists.txt
(cmake版本为3.9.6):
cmake_minimum_required(VERSION 3.0)
set(CMAKE_BUILD_TYPE Release)
if(APPLE)
set(CMAKE_SHARED_LIBRARY_SUFFIX ".so")
endif(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -v -lstdc++ -lpython2.7 -lboost_python")
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
add_library(boost_python_example SHARED main.cpp)
set_target_properties(boost_python_example PROPERTIES PREFIX "")
然后,通过执行make clean && cmake . && make
make clean && cmake . && make
,我获得了所需的库boost_python_example.so
并将其路径添加到PYTHONPATH
。 现在,我的代码可以从Python成功导入了,但是在执行方法时会以各种方式崩溃:
user-osx1:BoostPythonTest user$ python
Python 2.7.14 |Anaconda, Inc.| (default, Oct 5 2017, 02:28:52)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import boost_python_example
>>> from boost_python_example import *
>>> square(5)
Segmentation fault: 11
user-osx1:BoostPythonTest user$ python
Python 2.7.14 |Anaconda, Inc.| (default, Oct 5 2017, 02:28:52)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from boost_python_example import *
>>> greet()
Fatal Python error: PyEval_SaveThread: NULL tstate
Abort trap: 6
user-osx1:BoostPythonTest user$ which python
/Users/user/anaconda2/bin/python
user-osx1:BoostPythonTest user$ python --version
Python 2.7.14 :: Anaconda, Inc.
我究竟做错了什么? 据我了解,当Boost.Python与用户的Python版本不兼容时,通常会发生此类错误。 这就是为什么我使用--build-from-source --with-python
选项重新安装Boost的原因,但没有帮助。
它是否缺少BOOST_PYTHON_MODULE
块中的PyEval_InitThreads()
调用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.