python指针更改结构字段

python指针更改结构字段

本文介绍了如何使用ctypes python指针更改结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我使用ctypes访问dll值的代码。

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 changes ,I can access the addresses and get changed values.

DUMMY_DLL_PATH = "dummyModel.dll"

class MyStruct(ctypes.Structure):
    _fields_ = [("field_one", ctypes.c_int),
                ("field_two", ctypes.c_int)]

d_m = ctypes.cdll.LoadLibrary(DUMMY_DLL_PATH)

d_i = MyStruct.in_dll(d_m,"dummy_In")

in_field = ctypes.c_int(d_i.field_one)

#storing the address
b = ctypes.addressof(in_field)
b_v = ctypes.cast(b,ctypes.POINTER(ctypes.c_int))

k= b_v.contents

print 'before',d_i.field_one,k.value
#changing the value
d_i.field_one = 10

print 'After',d_i.field_one,k.value



输出:



Output:

Before 0 0
After 10 0

通过指针,值未更改。仍为0

Through pointers, the values are not getting changed.remains 0

推荐答案

问题是 in_field 是新的 c_int 对象占用与原始结构不同的内存。您想要的是 c_int.from_buffer (),它共享原始对象的内存。下面是一个示例:

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:

struct MyStruct
{
    int one;
    int two;
};

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



Python脚本:



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)

这篇关于如何使用ctypes python指针更改结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:16