python - 使用 boost::python 手动构建共享对象

标签 python c++ macos boost-python

我正在尝试使用 boost::python(通过自制软件安装)创建一个共享对象,它可以使用操作系统附带的 Python 2.7 在 OS X 上的 Python 中加载。我必须链接哪些库才能获得可用的共享对象?

这里是 hello_ext.cpp,摘自教程

// hello_ext.cpp
char const* greet() {
  return "hello, world";
}

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext)
{
  using namespace boost::python;
  def("greet", greet);
}

我可以像这样编译这个例子,虽然它需要一段时间。

$ clang++ -fPIC -c -I/usr/include/python2.7 hello_ext.cpp

但是,当我尝试链接它并生成 so 时,我得到了一堆 undefined symbol :

$ clang++ -shared -o hello_ext.so hello_ext.o | & head -n 7
Undefined symbols for architecture x86_64:
  "_PyString_Type", referenced from:
      boost::python::to_python_value<char const* const&>::get_pytype() const in hello_ext.o
  "__Py_NoneStruct", referenced from:
      boost::python::api::object::object() in hello_ext.o
  "boost::python::detail::init_module(char const*, void (*)())", referenced from:
      _inithello_ext in hello_ext.o

其中一些明显来自Python解释器,确实-lpython解决了一些 Unresolved 符号错误:

$ clang++ -shared -o hello_ext.so hello_ext.o -lpython | & head -n 7
Undefined symbols for architecture x86_64:
  "boost::python::detail::init_module(char const*, void (*)())", referenced from:
      _inithello_ext in hello_ext.o
  "boost::python::detail::gcc_demangle(char const*)", referenced from:
      boost::python::type_info::name() const in hello_ext.o
  "boost::python::detail::scope_setattr_doc(char const*, boost::python::api::object const&, char const*)", referenced from:
      void boost::python::def<char const* (*)()>(char const*, char const* (*)()) in hello_ext.o

文档 here对于 boost::python 详细介绍了如何将库与 cmake 结合使用,但没有详细说明链接时需要哪些库。

最佳答案

boost::python 不是一个只有头文件的库,它包括一个二进制组件。你需要与之链接,例如

clang++ ... -I/usr/include/python2.7 -lboost_python -lpython2.7  

该库显然是由自制程序包 boost-python 安装的,而不是 boost

关于python - 使用 boost::python 手动构建共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48921541/

相关文章:

python - 如何近似大型稀疏 scipy 矩阵中的相关矩阵?

c++ - 如何通过 AST 为访问者模式解决 C++ 中的 header 重复问题

javascript - Electron - 如何更改 Electron 添加的默认 .icns

c++ - 从文件中读取不正确的数据(C++、fstream)

c++ - 使用 C++ future 作为函数堆栈中的中间值会导致段错误

objective-c - Mac 上 plist 文件中的 MS Word 2011 自定义词典项目格式

c++ - 从 .dylib 转换为 .so

Python Pandas "Error: Could not install packages due to an OSError: No such file or directory:"

python - Docker X11 Forward 得到黑屏

python - R-Python : how to eliminate specific rows and columns?