1、linuxany.c代碼如下:
#include "stdio.h" void display(char* msg){ printf("%s ",msg); } int add(int a,int b){ return a+b; }
2、編譯c代碼,最后生成Python可執行的.so文件
(1)gcc -c linuxany.c,將生成一個linuxany.o文件
(2)gcc -shared linuxany.c -o linuxany.so,將生成一個linuxany.so文件
3、在Python中調用
#!/usr/bin/python from ctypes import * import os //參數為生成的.so文件所在的絕對路徑 libtest = cdll.LoadLibrary(os.getcwd() + '/linuxany.so') //直接用方法名進行調用 print libtest.display('Hello,I am linuxany.com') print libtest.add(2,2010)
4、運行結果
Hello,I am linuxany.com 2012
Windows下Python調用dll
python中如果要調用dll,需要用到ctypes模塊,在程序開頭導入模塊 import ctypes
由于調用約定的不同,python調用dll的方法也不同,主要有兩種調用規則,即 cdecl和stdcal,還有其他的一些調用約定,關于他們的不同,可以查閱其他資料
先說 stdcal的調用方法:
方法一:
import ctypes dll = ctypes.windll.LoadLibrary( 'test.dll' )
方法二:
import ctypes dll = ctypes.WinDll( 'test.dll' )
cdecl的調用方法:
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
導出函數如下:
# 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] #參數類型 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
結果如下:
我們看到兩個結果,第一個是進行計算,第二個是帶回一個參數。
當然我們還可以很方便的使用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)
運行結果如下:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com