Python 不知道 C++ 文件,它只会知道从 C++ 文件编译的 扩展模块。这个扩展模块是一个目标文件,称为共享库。这个文件有一个界面,看起来 Python 就好像它是一个普通的 Python 模块。
只有在您告诉编译器编译 C++ 文件并将其与所需的所有库链接后,此目标文件才会存在。当然,需要的第一个库是 Boost.Python 本身,它必须在您正在编译的系统上可用。
您可以告诉 Python 为您编译 C++ 文件,这样您就不需要弄乱编译器及其库标志。为此,您需要一个名为 setup.py 的文件,您可以在其中使用 Setuptools 库或标准 Distutils 来定义如何在系统上安装其他 Python 模块。安装步骤之一是编译所有扩展模块,称为build_ext 阶段。
让我们假设您有以下目录和文件:
hello-world/
├── hello_ext.cpp
└── setup.py
setup.py的内容是:
from distutils.core import setup
from distutils.extension import Extension
hello_ext = Extension(
'hello_ext',
sources=['hello_ext.cpp'],
include_dirs=['/opt/local/include'],
libraries=['boost_python-mt'],
library_dirs=['/opt/local/lib'])
setup(
name='hello-world',
version='0.1',
ext_modules=[hello_ext])
如您所见,我们告诉 Python 有一个我们要编译的扩展,源文件在哪里,以及包含的库在哪里。 这取决于系统。此处显示的示例适用于 Mac OS X 系统,其中 Boost 库是通过 MacPorts 安装的。
hello_ext.cpp 的内容如教程中所示,但请注意重新排序,以便BOOST_PYTHON_MODULE 宏出现在必须导出到 Python 的任何定义之后:::: p>
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
然后您可以通过在命令行上执行以下命令来告诉 Python 为您编译和链接:
$ python setup.py build_ext --inplace
running build_ext
building 'hello_ext' extension
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -pipe -Os -fwrapv -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/opt/local/include -I/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c hello_ext.cpp -o build/temp.macosx-10.9-x86_64-2.7/hello_ext.o
/usr/bin/clang++ -bundle -undefined dynamic_lookup -L/opt/local/lib -Wl,-headerpad_max_install_names -L/opt/local/lib/db46 build/temp.macosx-10.9-x86_64-2.7/hello_ext.o -L/opt/local/lib -lboost_python-mt -o ./hello_ext.so
(--inplace 标志告诉 Python 将编译的产品留在源文件旁边。默认是将它们移动到 build 目录,以保持源目录干净。)
之后,您将在hello-world 目录中找到一个名为hello_ext.dll(或在Unix 上为hello_ext.so)的新文件。如果您在该目录中启动 Python 解释器,您将能够导入模块 hello_ext 并使用函数 greet,如 Boost 教程中所示。