python - c++ boost python列表提取导致段错误

标签 python c++ boost

我在使用 boost python 时遇到了一个奇怪的问题。在尝试对我的一些代码进行单元测试时,我发现在创建 boost::python::list 并将信息附加到它之后,尝试提取该数据会导致段错误。下面是我的问题的一个简单示例。

main.cpp

#include <boost/python.hpp>

int main()
{
    boost::python::list testList;
    float a = 1.12;
    testList.append(a);

    // This line results in a seg fault
    float b = boost::python::extract<float>(testList[0]);
    return 0;
}

还有我的CMakeLists.txt

cmake_minimum_required(VERSION 2.8.3)
project(boost_python_test)

find_package(Boost REQUIRED COMPONENTS system thread python)
find_package(PythonLibs REQUIRED)

IF(Boost_FOUND)
  SET(Boost_USE_STATIC_LIBS OFF)
  SET(Boost_USE_MULTITHREADED ON)
  SET(Boost_USE_STATIC_RUNTIME OFF)
ENDIF()

set(SOURCES_DIRECTORY ${PROJECT_SOURCE_DIR}/src)

set(PROJECT_SOURCES
${SOURCES_DIRECTORY}/main.cpp
)


include_directories(${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})

## Declare a cpp executable
add_executable(${PROJECT_NAME}
${SOURCES_DIRECTORY}/main.cpp
)

target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})

编译器输出为:

-- The C compiler identification is GNU 4.8.2
-- The CXX compiler identification is GNU 4.8.2
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Boost version: 1.54.0
-- Found the following Boost libraries:
--   system
--   thread
--   python
-- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so (found     version "2.7.6") 
-- Configuring done
-- Generating done
-- Build files have been written to:         /home/jordan/Git/boost_python_test/build

最佳答案

你将不得不使用 Py_Initialize 来让它工作。查看 Embedding Python . @eacousineau 是这个解决方案背后的人和真正的大脑。

#include <boost/python.hpp>

int main()
{
    // Need this line for it to work
    Py_Initialize();
    boost::python::list testList;
    float a = 1.12;
    testList.append(a);

    // This line no longer results in a seg fault
    float b = boost::python::extract<float>(testList[0]);
    return 0;
}

关于python - c++ boost python列表提取导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325245/

相关文章:

python - 使用 Tensorflow,使用神经网络进行 2 类分类

python - 使用 Spark 将文本文件导出到 PostgreSQL - 自动化

c++ - sizeof 运算符是否更喜欢对象而不是类型?

c++ - 在类对象段错误中使用 boost::interprocess ,为什么?

C++/Boost 模板运行时多态性

python - 将 gRPC python 服务器与 ruby​​ 客户端一起使用时遇到的问题

python - 我如何像在 Illustrator 中一样在 python 中格式化文本?

c++ - 我应该如何读取 FILE_NOTIFY_INFORMATION 结构中的文件名

c++ - 反转非 ASCII 字符的字符串

c++ - 使用 boost::format 作为符号值打印 bool 值?