在使用boost::python
时,我真的很困惑于初始化c++类。当用CMake编译以下代码时,我没有得到任何错误,警告或其他东西:
#include <boost/python.hpp>
#include <iostream>
class Test {
public:
Test(int x);
~Test();
};
void greet() {
Test test(10);
std::cout << "Test" << std::endl;
}
BOOST_PYTHON_MODULE(libTestName)
{
Py_Initialize();
using namespace boost::python;
def("greet", greet);
}
与以下CMakeLists.txt
:
cmake_minimum_required (VERSION 3.8)
project (libTestLib)
IF(NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE "RELEASE")
ENDIF()
# Add all the files to the library so it can get created
ADD_LIBRARY(TestLib SHARED
main.cpp)
# Set the Flags and the CXX command
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fconcepts")
set(boostPython python3)
find_package(PythonInterp 3.6 REQUIRED)
find_package(PythonLibs 3.6 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
FIND_PACKAGE(Boost REQUIRED COMPONENTS system program_options numpy ${boostPython})
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(TestLib ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})
else()
message(FATAL_ERROR "Could not find boost.")
endif()
当我尝试将此库导入Python时,我得到以下错误代码:
>>> import build.libPathFinding
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: path/to/lib/libTestLib.so: undefined symbol: _ZN4TestD1Ev
我fuígured发现可以用下面的代码创建一个指向新对象的指针:
void greet() {
Test *test = new Test(10);
std::cout << "Test" << std::endl;
}
但是我无法通过delete再次释放这个指针,因为我将再次从Python获得导入错误。
只使用一个构造函数和析构函数:
#include <boost/python.hpp>
#include <iostream>
class Test {
public:
Test(int x) {}; // Change
~Test() {}; // Change
};
void greet() {
Test test(10);
std::cout << "Test" << std::endl;
}
BOOST_PYTHON_MODULE(libTestName)
{
Py_Initialize();
using namespace boost::python;
def("greet", greet);
}