推荐学习书目
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
simple2025
0D
V2EX  ›  Python

问下 ctypes 的问题

  •  
  •   simple2025 · Nov 28, 2018 · 1410 views
    This topic created in 2749 days ago, the information mentioned may be changed or developed.

    有个 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 replies    2018-11-28 17:20:27 +08:00
    wwqgtxx
        1
    wwqgtxx  
       Nov 28, 2018   ❤️ 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
    simple2025
        2
    simple2025  
    OP
       Nov 28, 2018
    @wwqgtxx 但是我用 create_string_buff 也出问题了,结果不对
    wwqgtxx
        3
    wwqgtxx  
       Nov 28, 2018 via iPhone   ❤️ 1
    你先自己写个 dll 直接 printf pbuff 看看你传进去的数据是否和 dephi 传进去的一样的再找别的原因
    simple2025
        4
    simple2025  
    OP
       Nov 28, 2018
    @chenqh 好的,谢谢大佬
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3921 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:17 · PVG 18:17 · LAX 03:17 · JFK 06:17
    ♥ Do have faith in what you're doing.