作者:刘宾, [email protected]
请尊重作者著作权,转载请注明出处,谢谢!
类型表
ctype type | C type | python type |
---|---|---|
c_bool | _Bool | bool |
c_char | char | 1-character bytes object |
c_wchar | wchar_t | 1-character string |
c_byte | char | int |
c_ubyte | unsigned char | int |
c_short | short | int |
c_ushort | unsigned short | int |
c_int | int | int |
c_uint | unsigned int | int |
c_long | long | int |
c_ulong | unsigned long | int |
c_longlong | __int64 or long long | int |
c_ulonglong | unsigned __int64 or unsigned long long | int |
c_size_t | size_t | int |
c_ssize_t | ssize_t or Py_ssize_t | int |
c_float | float | float |
c_double | double | float |
c_longdouble | long double | float |
c_char_p | char * (NUL terminated) | bytes object or None |
c_wchar_p | wchar_t * (NUL terminated) | string or None |
c_void_p | void * | int or None |
加载DLL
- 标准cdecl调用
dll = ctypes.CDLL("dllpath")
- Win dll
dll = ctypes.WinDLL("dllpath")
调用dll中方法
- 函数返回类型,函数默认返回c_int类型,如果需要返回其他类型,需要设置函数的restype属性
dll.method_in_dll.restype = ctypes.c_short
- 调用方法
ret = dll.method_in_dll()
数据类型转换
- 指针
# 取对象指针
ptr = ctypes.pointer(ct_obj)
ptr.contents 为 ct_obj
# 初始化空指针
ptr = ctypes.POINTER(ctypes.c_int)
# 字符串对象
obj = c_wchar_p("Hello, World")
obj
c_wchar_p('Hello, World')
obj.value
u'Hello, World'
# 缓冲区
# create a 3 byte buffer, initialized to NUL bytes
p = create_string_buffer(3)
# create a buffer containing a NUL terminated string
p = create_string_buffer(b"Hello")
# create a 10 byte buffer
p = create_string_buffer(b"Hello", 10)
- 引用
ref = ctypes.byref(ct_obj)
- 普通类型
i = c_int(42)
print i.value
- 数组
buf = c_int * 10
m = buf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print m[1]
- 结构体和联合
class IODBPSD(ct.Structure):
""" CNC parameter """
class IODBDATA(ct.Union):
class REALPRM(ct.Structure):
_fields_ = [('prm_val', ct.c_long),
('dec_val', ct.c_long)]
_fields_ = [('cdata', ct.c_byte),
('idata', ct.c_short),
('ldata', ct.c_long),
('rdata', REALPRM),
('cdatas', ct.c_byte*f_globalv.MAX_AXIS),
('idatas', ct.c_short*f_globalv.MAX_AXIS),
('ldatas', ct.c_long*f_globalv.MAX_AXIS),
('rdatas', REALPRM*f_globalv.MAX_AXIS)]
_anonymous_ = ('u',)
_fields_ = [('datano', ct.c_short),
('type', ct.c_short),
('u', IODBDATA)]
- bitmap,仅对int有效
class Int(Structure):
_fields_ = [("first_16", c_int, 16),
("second_16", c_int, 16)]
- 链表
class Test(Structure):
pass
Test._fields_ = [('x', c_int),
('y', c_char),
('next', POINTER(Test))]