C++ Boost .Python:2个问题

2024-05-13 22:04:48 发布

您现在位置:Python中文网/ 问答频道 /正文

<> >,我搜索了一个很好的工具来集成我的C++代码和Python,首先我看了BooSt.python。

我从boost文档中获得了hello examle并尝试构建和运行它。源代码是(src/hello.cpp):

#include <Python.h>
#include <boost/python.hpp>

char const* greet()
{
   return "hello, world";
}

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

问题1-Windows和mingw

我试图建立和我的结果:

g++ -o build\hello.o -c -IE:\Programming\libs\boost_1_48_0 -IE:\Programming\Python\include src\hello.cpp
g++ -shared -o pyhello.dll build\hello.o -LE:\Programming\libs\boost_1_48_0\stage\lib -LE:\Programming\Python\libs -lboost_python-mgw45-mt-1_48 -lpython27 -Wl,--out-implib,libpyhello.a
Creating library file: libpyhello.a
build\hello.o:hello.cpp:(.text+0x20): undefined reference to `_imp___ZN5boost6python6detail11init_moduleEPKcPFvvE'

还有与boost::python类似的4个未定义错误。

我的build boost命令行:bjam toolset=gcc variant=release

我在google(和stackoverflow)也发现了类似的问题,但在我的案例中没有找到答案。

问题2-使用模块(linux)

在linux平台上,构建模块没有问题,同一个源代码编译得很好:

g++ -o build/hello.os -c -fPIC -I/usr/include/python2.7 src/hello.cpp
g++ -o libpyhello.so -shared build/hello.os -lboost_python -lpython2.7

现在,我该怎么用呢?在文档中,没有关于模块命名的文字,请引用:

can be exposed to Python by writing a Boost.Python wrapper:

#include <boost/python.hpp>

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

That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:

>>> import hello_ext
>>> print hello_ext.greet()
hello, world

所以,我的模块名为:libpyhello.So,但是如何在pythoniterpeter中使用它呢?我尝试导入pyhello,hello_ext,libpyhello-只有使用libpyhello解释器才能打印:

ImportError: dynamic module does not define init function (initlibpyhello)

导入的所有其他变体都失败,原因是:ImportError: No module named pyhello

更新第二个问题:已解决,*.so模块必须命名为BOOST_PYTHON_模块中使用的ID。在我将BOOST_PYTHON_MODULE(hello_ext)更改为BOOST_PYTHON_MODULE(libpyhello)之后,模块将与libpyhello一起导入。


Tags: 模块buildsrchelloincludecppextlibs
2条回答

嗨,我和你在win7 32bitmingw下遇到了同样的问题,不过我最后还是解决了。

可能的解决方案是:

生成lib boost python时,请改用link=shared。

比如:

bjam stage toolset=gcc --with-python link=shared threading=multi runtime-link=shared variant=release,debug --user-config=user-config.jam cxxflags="-include cmath "

链接时,显式使用BOOST_PYTHON_STATIC_LIB宏

下面是示例cmd行:

g++ hello_ext.cpp -shared -O3 -DBOOST_PYTHON_STATIC_LIB -lboost_python  -lpython25 -o hello_ext.pyd

为了节省时间,只需在文件boost\python.hpp中添加一些行:

#include <cmath>   //fix  cmath:1096:11: error: '::hypot' has not been declared
#if defined(__MINGW32__) && defined(_WIN32)
#if !defined(BOOST_PYTHON_SOURCE)
#define BOOST_PYTHON_STATIC_LIB
#endif 
#endif 
... here,other includes files ...

然后,您可以像这样简单地使用cmd

g++ hello_ext.cpp -shared -lboost_python  -lpython25 -o hello_ext.pyd 

这个壳没问题,试试看。

库文件的命名方式必须与在此处声明模块的方式相同,这一点很重要:

BOOST_PYTHON_MODULE(hello_ext)

hello_ext.dllhello_ext.so

相关问题 更多 >