不能免俗,先打印个helloworld出来,c代码的函数
hello.c
#include <stdio.h> int helloworld() { printf("hello world!"); return 0; }
然后编译成动态链接库
gcc hello.c -fPIC -shared -o libhello.so
最后在python中引入ctypes这个包,然后通过一个对dlopen包装的CDLL就可以引用so中的代码
import ctypes so=ctypes.CDLL("./libhello.so") so.helloworld()
python3和python都能够执行
python3 main.py
hello world!
python main.py
hello world!
python仅仅支持c代码的这种方式,如果使用c++的编译器,则会报错,例如仅仅是把文件名称替换为hello.cpp
gcc hello.cpp -fPIC -shared -o libhello.so
此时再执行
python ./main.py
则出现这种错误
Traceback (most recent call last): File "./main.py", line 15, in <module> so=ctypes.CDLL("./libhello.so") File "/usr/local/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: ./libhello.so: undefined symbol: __gxx_personality_v0
用g++更错
g++ hello.cpp -fPIC -shared -o libhello.so
则出现
Traceback (most recent call last): File "./main.py", line 16, in <module> so.helloworld() File "/usr/local/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__ func = self.__getitem__(name) File "/usr/local/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: ./libhello.so: undefined symbol: helloworld