python使用c扩展库

参考来源:https://www.cnblogs.com/yssjun/p/9960479.html

直观例子:

import ctypes, platform, time
if platform.system() == 'Windows':
libc = ctypes.cdll.LoadLibrary('msvcrt.dll')
elif platform.system() == 'Linux':
libc = ctypes.cdll.LoadLibrary('libc.so.6')
print libc

Example 1

libc.printf('%s\n', 'lib c printf function')
libc.printf('%s\n', ctypes.c_char_p('lib c printf function with c_char_p'))
libc.printf('%ls\n', ctypes.c_wchar_p(u'lib c printf function with c_wchar_p'))
libc.printf('%d\n', 12)
libc.printf('%f\n', ctypes.c_double(1.2))

Example 2

libc.sin.restype = ctypes.c_double
print libc.sin(ctypes.c_double(30 * 3.14 / 180))

Example 3

libc.pow.restype = ctypes.c_double
print libc.pow(ctypes.c_double(2), ctypes.c_double(10))

Example 4

print libc.time(), time.time()

Example 5

libc.strcpy.restype = ctypes.c_char_p
res = 'Hello'
print libc.strcpy(ctypes.c_char_p(res), ctypes.c_char_p('World'))
print res

posted @ 2020-04-08 18:10  bhz  阅读(467)  评论(0编辑  收藏  举报