2017-03-17 33 views
1

我要創建我的共享庫Python擴展。我能夠使用distutils來構建和安裝它。然而,當我導入模塊時得到「未定義的符號」錯誤。Python擴展不加載我的共享庫

說我的共享庫「libhello.so」包含一個函數。

#include <stdio.h> 
void hello(void) { 
    printf("Hello world\n"); 
} 
g++ -fPIC hello.c -shared -o libhello.so 
$ file libhello.so 
    libhello.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped 

這是我的setup.py

#!/usr/bin/env python 

from distutils.core import setup, Extension 

vendor_lib = '/home/sanjeev/trial1/vendor' 

module1 = Extension("hello", 
        sources = ["hellomodule.c"], 
        include_dirs = [vendor_lib], 
        library_dirs = [vendor_lib], 
        runtime_library_dirs = [vendor_lib], 
        libraries = ['hello']) 

setup(name = 'foo', 
     version = '1.0', 
     description = 'trying to link extern lib', 
     ext_modules = [module1]) 

上運行安裝程序

$ python setup.py install --home install 
$ cd install/lib/python 
$ python 
Python 2.7.2 (default, Aug 5 2011, 13:36:11) 
[GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import platform 
>>> platform.architecture() 
('64bit', 'ELF') 

>>> import hello 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: ./hello.so: undefined symbol: hello 

回答

1

libhello.sog++編譯,而你沒有extern "C"hello功能,所以它得到了名字破損。

您的hello.so擴展名爲推測爲編譯gcc,它發出一個引用到未加密的符號。

編譯hello.cgcc,或更改hello.c到:

#include <stdio.h> 

extern "C" void hello(void); 

void hello(void) { 
    printf("Hello world\n"); 
} 

的情況下,其中一個功能是在一個編譯單元定義,並從另一個叫,你應該把一個函數原型在頭文件,包括它在這兩個編譯單元,使他們同意的聯繫和簽名。

#ifndef hello_h_included 
#define hello_h_included 

#ifdef __cplusplus 
extern "C" { 
#endif 

void hello(void); 

#ifdef __cplusplus 
} 
#endif 

#endif // hello_h_included 
+0

作品。是的,這是問題所在。 –