ctypes使得python能夠直接調用c語言開發的動態鏈接庫,非常強大。
爲了使用CTypes,你必須依次完成以下步驟:
* 編寫動態連接庫程序
* 載入動態連接庫
* 將Python的對象轉換爲ctypes所能識別的參數
* 使用ctypes的參數調用動態連接庫中的函數
一、Windows下使用Python的ctypes調用Dll動態鏈接庫
- 編寫dll文件
打開VS2008,新建一個VC工程,選擇Win32類型,Win32項目,用程序類型選擇DLL………
調用方式見Linux調用方式。
二、Linux下使用Python的ctypes調用so動態鏈接庫
- 編寫so文件
1
//test.h
2
#include "stdio.h"
3
4
void
test();
5
float
add(
float
,
float
);
01
//test.c
02
#include "test.h"
03
04
void
test()
05
{
06
printf
(
"Hello Dll...\n"
);
07
}
08
09
float
add(
float
a,
float
b)
10
{
11
return
a + b;
12
}
1
gcc -fPIC -shared
test
.c -o libtest.so
2
3
#-fPIC 編譯成位置無關代碼,必須 不然你的程序在別的地方肯可能運行不了
4
#-shared 當然是說要編譯成共享庫了
- Python調用so動態鏈接庫
01
#!/usr/bin/env python
02
# -*-coding:UTF-8-*-
03
04
print
"sss"
05
06
from
ctypes
import
*
07
08
test
=
cdll.LoadLibrary(
"./libtest.so"
)
09
10
test.test()
11
12
add
=
test.add
13
add.argtypes
=
[c_float, c_float]
# 參數類型,兩個float(c_float內ctypes類型)
14
add.restype
=
c_float
15
16
print
add(
1.2
,
19.2
)
發
發的
Related posts:
- Flash/Python Socket之前使用Python socket都從socket.socket server_ …繼續閱讀 »...
- Python WebSocket Server手機中,使用HTML5中引入的WebSocket技術來取代PC端基於flash的 …繼續閱讀 »...
- Python 手冊[url]http://www.uplinux.com/download/doc …繼續閱讀 »...
- Linux中C/C++頭文件說明1、 Linux中一些頭文件的作用: <assert.h>:ANSI …繼續閱讀 »...
- 及時阻止SSH暴力破解入侵者方法最近,老是發現有很多暴力破解SSH密碼的入侵者,雖然服務器密碼設置的很複雜,但是 …繼續閱讀 »...
轉自:http://www.xinze.me/python-%E8%B0%83%E7%94%A8so-dll%E5%8A%A8%E6%80%81%E9%93%BE%E6%8E%A5%E5%BA%93/