动态链接库在Windows中为.dll文件,在linux中为.so文件。以linux平台为例说明python调用.so文件的使用方法。
c代码:
int max(int a,int b)
{
return a>b?a:b;
}
编译:gcc -fPIC -shared cma.c -o libmax.so
/*
* # -shared 为链接库 让编译器知道是要编译一个共享库
* # -fPIC(Position Independent Code) 编译生成代码与位置无关
*/
c++代码
#include<iostream>
using namespace std;
class TestLib
{
public:
void display();
void display(int a);
};
void TestLib::display() {
cout<<"First display"<<endl;
}
void TestLib::display(int a) {
cout<<"Second display:"<<a<<endl;
}
//C++想要编译成python可以调用的.so文件,必须加以下代码:
extern "C" {
TestLib obj;
void display() {
obj.display();
}
void display_int(int a) {
obj.display(a);
}
}
编译:g++ -shared -o 12.so 12.cpp
##g++编译生成动态库libpycall.so:g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp。
from ctypes import cdll
import ctypes
cur = cdll.LoadLibrary('./libmax.so')
a = cur.max(1, 20)
print(a)
so = ctypes.cdll.LoadLibrary
# lib = so("./libdisplay.so")
lib = so("./libdisplay.so")
print('display()')
lib.display()
print('display(100)')
lib.display_int(ctypes.c_int(100))