gpt4 book ai didi

python - 如何使用 ctypes python 指针更改结构字段

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:16 25 4
gpt4 key购买 nike

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

我的意图是存储结构字段地址。每当结构中的值发生变化时,我都可以访问地址并获取更改后的值。

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

输出:

Before 0 0  
After 10 0

通过指针,值不会改变。保持为 0

最佳答案

问题是 in_field 是一个新的 c_int 对象,占用的内存与原始结构不同。你想要的是共享原始对象内存的 c_int.from_buffer ( docs )。这是一个例子:

cl/LD x.c编译的Windows DLL源x.c:

struct MyStruct
{
int one;
int two;
};

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

Python 脚本:

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

输出:

MyStruct(1,2)
before c_long(1) c_long(2)
after c_long(10) c_long(20)

关于python - 如何使用 ctypes python 指针更改结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12174008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com