2012-06-10 14 views
16
[[email protected] python]$ cat hello_world.cc 
#include <string> 
#include <Python.h> 
#include <boost/python.hpp> 

namespace { 
    std::string greet() { return "Helloworld"; } 
} 

using namespace boost::python; 

BOOST_PYTHON_MODULE(hello_world) 
{ 
    def("greet",greet); 
} 

[[email protected] python]$ g++ -c -fPIC hello_world.cc -I/path/to/boost/headers -I/path/to/python/headers -o hello_world.o 
[[email protected] python]$ g++ -shared -Wl,-soname,libhello_world.so -o libhello_world.so hello_world.o 
[[email protected] python]$ python 
Python 2.7.1 (r271:86832, Jan 10 2011, 09:46:57) 
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.path.append('.') 
>>> import hello_world 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: No module named hello_world 
>>> 

私は上記のように.soファイルを作成しましたが、私はpythonの中にインポートすることができません。私は何が欠けていますか?.soファイルからpythonモジュールをインポートするには?

答えて

8

libhello_world.soではなく、hello_world.soとする必要があります。

+2

感謝。今すぐImportErrorを取得します:./hello_world.so:undefined symbol:_ZNK12boost_1_47_06python7objects21py_function_impl_base9max_arityEv' – balki

+1

@balki:あなたはBoost.Pythonとリンクしていません。 –

+0

私はboost_pythonとリンクしていますが、今は 'ImportError:libboost_python:共有オブジェクトファイルを開くことができません:そのようなファイルやディレクトリはありません。 'LD_LIBRARY_PATH =/path/to/boost_python_lib'をエクスポートするとうまくいきます。 cmdlineでの指定方法は? – balki

13

'hello_world.so'ファイルをとり、 'hello_world.py'という名前の新しいpythonファイルを(同じディレクトリ内に)作成します。 それに以下のコードを入れてください。

def __bootstrap__(): 
    global __bootstrap__, __loader__, __file__ 
    import sys, pkg_resources, imp 
    __file__ = pkg_resources.resource_filename(__name__,'hello_world.so') 
    __loader__ = None; del __bootstrap__, __loader__ 
    imp.load_dynamic(__name__,__file__) 
__bootstrap__() 

今あなたは、このhello_worldをインポートすることができます。

>>> import hello_world 
+2

"\ __ bootstrap__"の名前を "\ _bootstrap"に変更する必要がありますか?特別な予約語だと思ってドキュメントを探すのに多くの時間を費やしましたが、何も見つかりませんでした。 https://www.python.org/dev/peps/pep-0008/#naming-conventions:\ __ double_leading_and_trailing_underscore__: "魔法の"オブジェクトまたはユーザー制御の名前空間に存在する属性。例えば。 \ __ init__、\ __ import__または\ __ file__です。そのような名前を発明しないでください。文書化されているものだけを使用してください。 –

+0

私たちはコピーすることができますが、info.Howについての詳細をいくつか追加することができます。 – user765443

+0

私はモジュールのreadlineでこれを試しました。私は、readlineを持つapt-getとPythonのバージョン#1(2.7.12)をインストールしたのですが、もう一つのバージョン#2(2.7.11)は単純に展開しました。そこで、バージョン2のsys.pathにあるディレクトリの1つにreadline.pyを追加し、/usr/lib/python2.7/lib-dynload/readline.x86_64-linux-gnuに同じディレクトリにシンボリックリンクを追加しました。バージョン1から。私はまだエラーが発生します。 –

関連する問題