我已经成功编译了Boost.Python'第一次尝试',但我不确定如何将其导入python并调用它包含的方法。我的源文件如下:
#include <stdlib.h>
#include <string>
#include <boost/python.hpp>
using namespace boost::python;
int test(int i)
{
fprintf(stderr, "%s:\n", __FUNCTION__);
return i * 5;
}
BOOST_PYTHON_MODULE(ipg)
{
using namespace boost::python;
def("test", test);
}
我的makefile包含:
# Which compiler?
CC=c++
# Which flags for object files?
OFLAGS=-c -Wall -fPIC
# Which flags for the output binary?
BFLAGS=-Wall -shared -o ipg
# Which flags for boost python?
BPFLAGS=-I/usr/include/python2.7
BLIBS=-lpython2.7 -lboost_python -lboost_system
# Make.
all: source/python.cpp
$(CC) $(BOUT) $(BFLAGS) $(BPFLAGS) $? $(BLIBS)
和我的测试脚本:
import sys
# My modules.
import ipg
ipg.test()
输出二进制文件与测试脚本一起放置,并运行测试脚本。这会导致以下错误:
Traceback(最近一次调用最后一次):文件“test.py”,第4行,in import ipg ImportError:没有名为ipg的模块
我应该使用哪些标志来编译输出二进制文件,我应该如何将其导入python?我以前在Windows上使用过boost.Python,但那是很久以前的事了。
答案 0 :(得分:6)
在Linux上,如果您的模块被调用ipg
,那么您需要创建一个名为ipg.so
的文件。这是一个简单的makefile;
ipg.o:
g++ -o ipg.o -c ipg.cc -Wall -fPIC -I/usr/include/python2.7
ipg.so: ipg.o
g++ -shared -o ipg.so ipg.o -lpython2.7 -lboost_python -lboost_system