2012-06-10 6 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 파일을 만들었지 만 파이썬 안에서 가져올 수 없습니다. 나는 무엇을 놓치고 있습니까?.so 파일에서 파이썬 모듈을 가져 오는 방법은 무엇입니까?

답변

8

libhello_world.so이 아니라 hello_world.so이라고해야합니다.

+2

감사 :

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를 가져올 수 있습니다. 이제 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'을 export하면 잘 동작합니다. cmdline에서 어떻게 지정합니까? – balki

13

'hello_world.so'파일을 가져 와서 'hello_world.py'라는 이름의 새로운 python 파일을 만듭니다 (같은 dir에 있음). 아래 코드를 입력하십시오 ...

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

복사 할 수는 있지만 정보에 대한 세부 정보를 추가 할 수는 있습니다. 어떻게 작동합니까? – user765443

+0

모듈 readline을 사용해 보았습니다. 나는 apt-get과 함께 설치된 python 버전 # 1 (2.7.12)와 readline을 가지고 있으며, 다른 버전 # 2 (2.7.11)은 단순히 확장되어 있습니다. 그래서 버전 2의 sys.path에있는 디렉토리 중 하나에 readline.py를 추가했고, /usr/lib/python2.7/lib-dynload/readline.x86_64-linux-gnu에 동일한 디렉토리에 심볼릭 링크를 추가했습니다. 그래서 버전 # 1에서. 나는 여전히 오류가 발생합니다. –

관련 문제