用python ctypes調用動態鏈接庫

[b]ctypes is very cool! Great piece of work.
- Just van Rossum[/b]
ctypes使得python能夠直接調用c語言開發的動態鏈接庫,非常強大。
爲了使用CTypes,你必須依次完成以下步驟:
* 編寫動態連接庫程序
* 載入動態連接庫
* 將Python的對象轉換爲ctypes所能識別的參數
* 使用ctypes的參數調用動態連接庫中的函數

來個簡單的實例吧:

1. 編寫動態鏈接庫


// filename: foo.c

#include <stdio.h>
char* myprint(char *str)
{
puts(str);
return str;
}

float add(float a, float b)
{
return a + b;
}


以上foo.c代碼,linux下編譯爲動態鏈接庫文件,命令是:

gcc -fPIC -shared foo.c -o foo.so


2. ctypes調用


#!/usr/bin/env python
# FILENAME: foo.py

from ctypes import *

foo = CDLL('./foo.so')

myprint = foo.myprint
myprint.argtypes = [POINTER(c_char)] # 參數類型,爲char指針
myprint.restype = c_char_p # 返回類型,同樣爲char指針
res = myprint('hello')
print res

add = foo.add
add.argtypes = [c_float, c_float] # 參數類型,兩個float(c_float內ctypes類型)
add.restype = c_float
print add(1.3, 4.2)



文檔請參考[url]http://docs.python.org/library/ctypes.html[/url]

3. 查找鏈接庫


>>> from ctypes.util import find_library
>>> find_library("m")
'libm.so.6'
>>> find_library("c")
'libc.so.6'
>>> find_library("bz2")
'libbz2.so.1.0'
>>>


調用libc裏的printf:

#filename: printf_example.py

import ctypes
from ctypes.util import find_library

printf = ctypes.CDLL(find_library("c")).printf

printf("hello, world\n")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章