Python在Windows和在Linux下調(diào)用動態(tài)鏈接庫的教程
Linux系統(tǒng)下調(diào)用動態(tài)庫(.so)
1、linuxany.c代碼如下:
#include "stdio.h"
void display(char* msg){
printf("%s\n",msg);
}
int add(int a,int b){
return a+b;
}
2、編譯c代碼,最后生成Python可執(zhí)行的.so文件
(1)gcc -c linuxany.c,將生成一個linuxany.o文件
(2)gcc -shared linuxany.c -o linuxany.so,將生成一個linuxany.so文件
3、在Python中調(diào)用
#!/usr/bin/python
from ctypes import *
import os
//參數(shù)為生成的.so文件所在的絕對路徑
libtest = cdll.LoadLibrary(os.getcwd() + '/linuxany.so')
//直接用方法名進行調(diào)用
print
libtest.display('Hello,I am linuxany.com')
print libtest.add(2,2010)
4、運行結果
Hello,I am linuxany.com 2012
Windows下Python調(diào)用dll
python中如果要調(diào)用dll,需要用到ctypes模塊,在程序開頭導入模塊 import ctypes
由于調(diào)用約定的不同,python調(diào)用dll的方法也不同,主要有兩種調(diào)用規(guī)則,即 cdecl和stdcal,還有其他的一些調(diào)用約定,關于他們的不同,可以查閱其他資料
先說 stdcal的調(diào)用方法:
方法一:
import ctypes dll = ctypes.windll.LoadLibrary( 'test.dll' )
方法二:
import ctypes dll = ctypes.WinDll( 'test.dll' )
cdecl的調(diào)用方法:
1.
import ctypes
dll = ctypes.cdll.LoadLibrary( 'test.dll' )
##注:一般在linux下為test.o文件,同樣可以使用如下的方法:
## dll = ctypes.cdll.LoadLibrary('test.o')
2.
import ctypes dll = ctypes.CDll( 'test.dll' )
看一個例子,首先編譯一個dll
導出函數(shù)如下:
# define ADD_EXPORT Q_DECL_EXPORT
extern "C" ADD_EXPORT int addnum(int num1,int num2)
{
return num1+num2;
}
extern "C" ADD_EXPORT void get_path(char *path){
memcpy(path,"hello",sizeof("hello"));
}
這里使用的是cdecl
腳本如下:
dll=ctypes.CDLL("add.dll")
add=dll.addnum
add.argtypes=[ctypes.c_int,ctypes.c_int] #參數(shù)類型
add.restypes=ctypes.c_int #返回值類型
print add(1,2)
get_path=dll.get_path
get_path.argtypes=[ctypes.c_char_p]
path=create_string_buffer(100)
get_path(path)
print path.value
結果如下:

我們看到兩個結果,第一個是進行計算,第二個是帶回一個參數(shù)。
當然我們還可以很方便的使用windows的dll,提供了很多接口
GetSystemDirectory = windll.kernel32.GetSystemDirectoryA buf = create_string_buffer(100) GetSystemDirectory(buf,100) print buf.value MessageBox = windll.user32.MessageBoxW MessageBox(None, u"Hello World", u"Hi", 0)
運行結果如下:

相關文章
torch.utils.data.DataLoader與迭代器轉(zhuǎn)換操作
這篇文章主要介紹了torch.utils.data.DataLoader與迭代器轉(zhuǎn)換操作,文章內(nèi)容接受非常詳細,對正在學習或工作的你有一定的幫助,需要的朋友可以參考一下2022-02-02
python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式
這篇文章主要介紹了python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

