Python扩展不加载我的共享库
问题描述:
我要创建我的共享库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
答
你libhello.so
被g++
编译,而你没有extern "C"
你hello
功能,所以它得到了名字破损。
您的hello.so
扩展名为推测为编译gcc
,它发出一个引用到未加密的符号。
编译hello.c
与gcc
,或更改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
作品。是的,这是问题所在。 –