国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python在Windows和在Linux下調(diào)用動態(tài)鏈接庫的教程

2019-11-25 17:05:27
字體:
供稿:網(wǎng)友

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、運行結(jié)果

Hello,I am linuxany.com2012 


Windows下Python調(diào)用dll

python中如果要調(diào)用dll,需要用到ctypes模塊,在程序開頭導(dǎo)入模塊 import ctypes

由于調(diào)用約定的不同,python調(diào)用dll的方法也不同,主要有兩種調(diào)用規(guī)則,即 cdecl和stdcal,還有其他的一些調(diào)用約定,關(guān)于他們的不同,可以查閱其他資料

先說 stdcal的調(diào)用方法:

方法一:

import ctypesdll = ctypes.windll.LoadLibrary( 'test.dll' )

方法二:

import ctypesdll = ctypes.WinDll( 'test.dll' )


cdecl的調(diào)用方法:

1.

import ctypesdll = ctypes.cdll.LoadLibrary( 'test.dll' )##注:一般在linux下為test.o文件,同樣可以使用如下的方法:## dll = ctypes.cdll.LoadLibrary('test.o')

2.

import ctypesdll = ctypes.CDll( 'test.dll' )

看一個例子,首先編譯一個dll

導(dǎo)出函數(shù)如下:

# define ADD_EXPORT Q_DECL_EXPORTextern "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.addnumadd.argtypes=[ctypes.c_int,ctypes.c_int] #參數(shù)類型add.restypes=ctypes.c_int            #返回值類型print add(1,2)get_path=dll.get_pathget_path.argtypes=[ctypes.c_char_p]path=create_string_buffer(100)get_path(path)print path.value

結(jié)果如下:

2015818121733886.gif (368×95)

我們看到兩個結(jié)果,第一個是進行計算,第二個是帶回一個參數(shù)。

當然我們還可以很方便的使用windows的dll,提供了很多接口

GetSystemDirectory = windll.kernel32.GetSystemDirectoryAbuf = create_string_buffer(100)GetSystemDirectory(buf,100)print buf.valueMessageBox = windll.user32.MessageBoxWMessageBox(None, u"Hello World", u"Hi", 0)

運行結(jié)果如下:

2015818121806575.gif (144×160)

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 深水埗区| 汉川市| 塘沽区| 兴安盟| 南召县| 新绛县| 滨海县| 交口县| 文安县| 清镇市| 涿州市| 连云港市| 乐都县| 黔东| 额尔古纳市| 永康市| 贵定县| 扬中市| 金坛市| 库尔勒市| 五峰| 大同市| 温宿县| 永和县| 道孚县| 朝阳市| 吴桥县| 分宜县| 云阳县| 依兰县| 巩留县| 牙克石市| 高要市| 珲春市| 金川县| 蓬安县| 东兴市| 图片| 石城县| 南部县| 盐源县|