2009年11月6日 星期五

Python ctypes 使用方法(1)

因為要使用C libray ,所以要使用ctypes 去 wrap C function
from ctypes import *
from ctypes.util import find_library

print '---Begin Show----'

print find_library('c')
print windll.kernel32
print cdll.msvcrt
print find_library('wapicd')
libc=cdll.LoadLibrary("msvcr90.dll")

print "---------- char --------"
x=c_char_p("Hello World")
print x
print x.value
print sizeof(x)

print '---------- int ----------'
i=c_int(42)
print i
print i.value

p = create_string_buffer("Hello", 10)
print sizeof(p), repr(p.raw)

print "---------- Bo class---------------"
class Bo(object):
def __init__(self, number):
self._as_parameter_=number

bo=Bo(33)
printf = libc.printf
printf("%d bottles of beer \n", bo)

strchr=libc.strchr
print strchr('abcdef', ord('c'))
strchr.restype=c_char_p # set retyrn type is char_pointer
print strchr('abcdef', ord('d'))


print '----Passing by reference---------'
i=c_int()
f=c_float()
s=create_string_buffer('\000'*32)
print i.value, f.value, repr(s.value)

libc.sscanf("1 3.14 hello", "%d %f %s", byref(i), byref(f), s) #Passing by ref
print i.value, f.value, repr(s.value)

print '---- Pointer ---------'
ptr_i=pointer(i)
ptr_f=pointer(f)
ptr_s=pointer(s)
libc.sscanf("1 3.14 hello", "%d %f %s", ptr_i,ptr_f,ptr_s)
print i.value, f.value, repr(s.value)
print 'point of i:', ptr_i.contents
print 'point of f:', ptr_f.contents
print 'point of s:', ptr_s.contents

print '------------ Test Structure ---------'
class POINT(Structure):
_fields_=[('x', c_int), ('y', c_int)]

p=POINT(10, 20)
print p.x, p.y

def testptr(a):
b=POINT()
b=a
b.x=a.x+100
b.y=a.y+100
return b


testptr.restype=POINT()
g=testptr(p)
print g.x, g.y



測試結果:

---Begin Show----
msvcr90.dll


C:\WINDOWS\system32\wapicd.dll
---------- char --------
c_char_p('Hello World')
Hello World
4
---------- int ----------
c_long(42)
42
10 'Hello\x00\x00\x00\x00\x00'
---------- Bo class---------------
12838358
def
----Passing by reference byref()---------
0 0.0 ''
1 3.1400001049 'hello'
---- Pointer pointer()---------
1 3.1400001049 'hello'
point of i: c_long(1)
point of f: c_float(3.1400001049041748)
point of s:
------------ Test Structure ---------
10 20
110 120




沒有留言: