V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
chenqh
V2EX  ›  Python

问下 ctypes 的问题

  •  
  •   chenqh · 2018-11-28 15:27:15 +08:00 · 1021 次点击
    这是一个创建于 2189 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有个 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 调用的不一样呀,

    4 条回复    2018-11-28 17:20:27 +08:00
    wwqgtxx
        1
    wwqgtxx  
       2018-11-28 15:44:01 +08:00   ❤️ 1
    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
        2
    chenqh  
    OP
       2018-11-28 16:26:28 +08:00
    @wwqgtxx 但是我用 create_string_buff 也出问题了,结果不对
    wwqgtxx
        3
    wwqgtxx  
       2018-11-28 16:41:02 +08:00 via iPhone   ❤️ 1
    你先自己写个 dll 直接 printf pbuff 看看你传进去的数据是否和 dephi 传进去的一样的再找别的原因
    chenqh
        4
    chenqh  
    OP
       2018-11-28 17:20:27 +08:00
    @chenqh 好的,谢谢大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1153 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 18:45 · PVG 02:45 · LAX 10:45 · JFK 13:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.