ctypes的应用笔记

ctypes

作用:c/c++与python混合编程的中间库
官方文档:https://docs.python.org/zh-cn/3/library/ctypes.html#

数据类型参照表:

c-typecpython
c_bool_Boolbool
c_charchar1-character bytes object
c_wcharwchar_t1-character string
c_bytecharint
c_ubyteunsigned charint
c_shortshortint
c_ushortunsigned shortint
c_intintint
c_uintunsigned intint
c_longlongint
c_ulongunsigned longint
c_longlong__int64 or long longint
c_ulonglongunsigned __int64 or unsigned long longint
c_size_tsize_tint
c_ssize_tssize_t or Py_ssize_tint
c_floatfloatfloat
c_doubledoublefloat
c_longdoublelong doublefloat
c_char_pchar * (NUL terminated)bytes object or None
c_wchar_pwchar_t * (NUL terminated)string or None
c_void_pvoid *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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值