问下 ctypes 的问题

2018-11-28 15:27:15 +08:00
 chenqh

有个 dll 的函数原型是这样

//C++原型 extern "C" __declspec(dllexport) void  __stdcall EncryptBuff(int lengthbuff,void* pbuff); 

c 代码里面会对 pbuff 做修改 py 代码

import os
from ctypes import *
PWD = os.path.dirname(os.path.abspath(__file__))
lib = windll.LoadLibrary(os.path.join(PWD, "buff1.dll")) # 要全路径
phone="18267919970".encode("utf-16").hex()[4:]
suff =  "0001410001000600010002"
all = "0001410001000600010002"+phone
print("len:", len(suff))
print("all:", all)
cmp = b"000141000100060001000231003800320036003700390031003900390037003000"
print(all==cmp)
print("slice:", all[20:22])
index = 20
p=c_void_p(bytes.fromhex(all[index:]))
print("p.value:",p.value, ",size:", sizeof(p))
lib.EncryptBuff(c_int(sizeof(p)), byref(p))
# print(p.value)
print(all[:index]+p.value.hex()[4:])

代码运行成功了,但是结果和 dephi 调用的不一样呀,

966 次点击
所在节点    Python
4 条回复
wwqgtxx
2018-11-28 15:44:01 +08:00
python 的 bytes 是不可变对象,直接用 C 代码修改他的底层数组会导致不可预见的结果,正确做法应该用 ctypes.create_string_buffer
>You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer() function which creates these in various ways. The current memory block contents can be accessed (or changed) with the raw property; if you want to access it as NUL terminated string, use the value property
chenqh
2018-11-28 16:26:28 +08:00
@wwqgtxx 但是我用 create_string_buff 也出问题了,结果不对
wwqgtxx
2018-11-28 16:41:02 +08:00
你先自己写个 dll 直接 printf pbuff 看看你传进去的数据是否和 dephi 传进去的一样的再找别的原因
chenqh
2018-11-28 17:20:27 +08:00
@chenqh 好的,谢谢大佬

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/512349

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX