gpt4 book ai didi

python - 从 Python 执行 C++ 代码时出现段错误——在 Mac OS 上使用 Boost.Python

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:38 25 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个库,以便可以在不同平台上使用 Python(尤其是 jupyter notebooks)中的方法。为此,我使用了 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 verison 是 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,我获得了所需的库 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 block 的 PyEval_InitThreads() 调用?

参见:Why is PyGILState_Release throwing Fatal Python Errors

关于python - 从 Python 执行 C++ 代码时出现段错误——在 Mac OS 上使用 Boost.Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com