ctypes
作用:c/c++与python混合编程的中间库
官方文档:https://docs.python.org/zh-cn/3/library/ctypes.html#
数据类型参照表:
c-type | c | python |
---|---|---|
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 |
函数
pass
常见问题
1、错误:OSError: [WinError 193] %1 不是有效的 Win32 应用程序
因为生成的dll是32位,使用vs生成64位的就行了
https://blog.csdn.net/qq_42214953/article/details/105628838
2、交互指针
https://blog.csdn.net/Kelvin_Yan/article/details/86546784
3、调用问题
https://blog.csdn.net/zx520113/article/details/85060765
4、.h文件
https://blog.csdn.net/magic_shuang/article/details/107898487?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-4&spm=1001.2101.3001.4242
5、__cdecl和__stdcall调用的问题
https://blog.csdn.net/zhangqi_gsts/article/details/50267851
示例
示例1 字符串调用问题
cpp中写如下函数
char * myAdd(int a[10],int b)
{
for (int i=0;i<10;i++){
a[i]=a[i]+b;
}
return "ok";
}
py中如下调用
test=windll.LoadLibrary('test.dll')
int10=c_int*10
a=int10(1,2,3,4,5,6,7,8,9,10)
b=c_int(2)
test.myAdd.restype=POINTER(c_char_p)
test.myAdd.argtypes=[POINTER(int10),c_int]#POINTER定义该类型的指针
d=test.myAdd(a,b)
print(string_at(d,2))#从指定地址开始,返回指定字符长度的字符串
print(type(a))
for i in a:
print(i)
示例2 结构体 指针问题
Type = c_double
class T(Structure):
_fields_ = [('x',c_uint16)]
class Test(Structure):
_fields_ = [('x',c_int),
('y',POINTER(Type)),#结构体内用指针
('z',T),#结构体内用结构体
]
if __name__ == '__main__':
data = POINTER(Type)(Type(1))#此处必须这样写
d = c_uint16(1)
qs_inst = T()
test = Test(1,data,qs_inst)
print(test.z.x)
print(test.y.contents)