Mac OS X上的Boost.Python Hello World

Wes*_*sey 9 python boost bjam boost-python

我正在尝试为Boost.Python设置和编译Hello World示例:http://www.boost.org/doc/libs/1_57_0/libs/python/doc/tutorial/doc/html/python/hello.html

我从Homebrew安装了bjam,boost,boost-build和boost-python:

brew install bjam
brew install boost
brew install boost-build
brew install boost-python
Run Code Online (Sandbox Code Playgroud)

我的python安装也是通过Homebrew.我不确定如何正确修改示例Jamroot文件,以便它与我的系统设置兼容.我将增强路径更改为: /usr/local/Cellar/boost;但我不确定需要更改的其他路径.当前设置给出了以下错误:

> bjam
notice: no Python configured in user-config.jam
notice: will use default configuration
Jamroot:26: in modules.load
*** argument error
* rule use-project ( id : where )
* called with: ( boost : /usr/local/Cellar/boost; project : requirements <library>/boost/python//boost_python <implicit-dependency>/boost//headers : usage-requirements <implicit-dependency>/boost//headers )
* extra argument project
/usr/local/share/boost-build/build/project.jam:1138:see definition of rule 'use-project' being called
/usr/local/share/boost-build/build/project.jam:311: in load-jamfile
/usr/local/share/boost-build/build/project.jam:64: in load
/usr/local/share/boost-build/build/project.jam:145: in project.find
/usr/local/share/boost-build/build-system.jam:535: in load
/usr/local/share/boost-build/kernel/modules.jam:289: in import
/usr/local/share/boost-build/kernel/bootstrap.jam:139: in boost-build
/usr/local/share/boost-build/boost-build.jam:8: in module scope
Run Code Online (Sandbox Code Playgroud)

Ale*_*ane 1

概括

  1. 不要使用BJAM它是浪费你的时间 - 我假设你的兴趣BJAM是让你的代码实际工作的副产品
  2. 是我的 github 页面的快速链接,我在其中做了一个hello_world示例using namespace boost::python
  3. 请参阅我的github,了解将多个 boost 文件链接到一个导入库中

更长的答案

我的设置和你一模一样。我花了很长时间才让它工作,因为文档真的很阴暗(如你所知),在你意识到之前,你就进入了一些奇怪的兔子洞,试图破解 make 文件和BJAM安装。

setup.py您可以像平常一样使用 a C,代码如下......

安装

homebrew您可以通过以下命令获取正确的boost-python :

brew install boost --with-python --build-from-source
Run Code Online (Sandbox Code Playgroud)

我认为brew install boost 应该可以工作,但这是一个很大的安装,而且两次安装的寿命很短

升压代码

假设以下代码在hello_ext.cpp

#include <boost/python.hpp>

char const* greet()
{
   return "Greetings!";
}

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}
Run Code Online (Sandbox Code Playgroud)

Python设置

然后你可以将setup.py文件写为

from distutils.core import setup
from distutils.extension import Extension

hello_ext = Extension(
    'hello_ext',
    sources=['hello_ext.cpp'],
    libraries=['boost_python-mt'],
)

setup(
    name='hello-world',
    version='0.1',
    ext_modules=[hello_ext])
Run Code Online (Sandbox Code Playgroud)

编译

以下示例可供以下人员使用:

python setup.py build_ext --inplace
Run Code Online (Sandbox Code Playgroud)

这将创建以下 build/ 目录和文件:

build/
hello_ext.so
Run Code Online (Sandbox Code Playgroud)

跑步

现在可以通过 python 直接调用:

In [1]: import hello_ext

In [2]: hello_ext.greet()
Out[2]: 'Greetings!'
Run Code Online (Sandbox Code Playgroud)