簡體   English   中英

C ++ Boost.Python:2個問題

[英]C++ Boost.Python : 2 problems

所以,我搜索好的工具將我的C ++代碼與python集成,起初我看了boost.python。

我從boost文檔中得到了問候語,並嘗試構建並運行它。 源代碼是(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個未定義的錯誤。

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

我在谷歌中找到了類似的麻煩(也在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

現在,我該如何使用它? 在文檔中沒有關於模塊命名的文字,引用:

可以通過編寫Boost.Python包裝器來暴露給Python:

 #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } 

而已。 我們完成了。 我們現在可以將其構建為共享庫。 現在可以看到生成的DLL。 這是一個Python會話示例:

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

所以,我的模塊名為:libpyhello.so,但我如何在python iterpreter中使用它? 我嘗試導入pyhello,hello_ext,libpyhello - 並且只打印了libpyhello解釋器:

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

所有其他導入變體都失敗了: ImportError: No module named pyhello

更新第2個問題 :已解決,* .so模塊必須命名為BOOST_PYTHON_MODULE中使用的ID。 在我改變: BOOST_PYTHON_MODULE(hello_ext)BOOST_PYTHON_MODULE(libpyhello) ,模塊被導入為libpyhello。

重要的是,庫文件的命名就像您在此處聲明模塊一樣:

BOOST_PYTHON_MODULE(hello_ext)

那就是hello_ext.dllhello_ext.so

嗨,我和mingwwin7 32bit下有同樣的問題,不過我最后修好了。

可能的解決方案是:

構建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 

這個shell會好的,試一試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM