How to change structure fields using ctypes python pointers

前端 未结 1 859
青春惊慌失措
青春惊慌失措 2021-01-24 09:26

Below is the code where I\'m accessing the values of dll using ctypes.

My intention is to store the structure fields addresses. Whenever the values in the structure chan

相关标签:
1条回答
  • 2021-01-24 10:19

    The problem is in_field is a new c_int object occupying different memory than the original structure. What you want is c_int.from_buffer (docs) which shares the memory of the original object. Here's an example:

    Windows DLL source x.c compiled with cl /LD x.c:

    struct MyStruct
    {
        int one;
        int two;
    };
    
    __declspec(dllexport) struct MyStruct myStruct = {1,2};
    

    Python script:

    from ctypes import *
    
    class MyStruct(Structure):
        _fields_ = [
            ("one", c_int),
            ("two", c_int)]
        def __repr__(self):
            return 'MyStruct({},{})'.format(self.one,self.two)
    
    dll = CDLL('x')
    struct = MyStruct.in_dll(dll,"myStruct")
    alias1 = c_int.from_buffer(struct, MyStruct.one.offset)
    alias2 = c_int.from_buffer(struct, MyStruct.two.offset)
    print struct
    print 'before',alias1,alias2
    struct.one = 10
    struct.two = 20
    print 'after',alias1,alias2
    

    Output:

    MyStruct(1,2)
    before c_long(1) c_long(2)
    after c_long(10) c_long(20)
    
    0 讨论(0)
提交回复
热议问题