python - 在 Python 中访问结构元素

标签 python ctypes

我在访问结构元素时遇到问题。请注意,我已经使用以下命令将一些内容读入结构中 sscanf(模拟我的实际例程)但Python似乎没有意识到这一点。所以我添加了一个声明 分配一个值,然后Python意识到那里有东西。这只发生在我阅读时 strcuture ...正如我读到的 c_ulong 一样,效果很好。

class vendrRecord(Structure):
    _pack_ = 1                                            # pack the struct
    _fields_ = [
        ("ytdPayments"           ,c_ulong),
        ]

VendrRecord = vendrRecord()
libc = cdll.msvcrt
libc.sscanf(b"1 2 3", b"%d", byref(VendrRecord))   # read something into the structure    
dsi_lib  = ctypes.cdll.LoadLibrary(find_library('DsiLibrary_dll'))  # using my library just to give access to a dump routine
dsi_lib.DsmDumpBytes( byref(VendrRecord), 4 )       # this prints 0000: 01 00 00 00

print(vendrRecord.ytdPayments)          # this prints <Field type=c_ulong, ofs=0, size=4>. I expected it to print 1 
vendrRecord.ytdPayments = 2
print(vendrRecord.ytdPayments)          # this prints 2

最佳答案

您正在打印类变量而不是实例变量(注意大小写):

from ctypes import *

class vendrRecord(Structure):
    _fields_ = [("ytdPayments",c_ulong)]

    VendrRecord = vendrRecord()
    libc = cdll.msvcrt
    libc.sscanf(b"1 2 3", b"%d", byref(VendrRecord))   # read something into the structure    
    print(vendrRecord.ytdPayments) # class name
    print(VendrRecord.ytdPayments) # instance name

输出:

<Field type=c_ulong, ofs=0, size=4>
1

关于python - 在 Python 中访问结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34696183/

相关文章:

python - 将具有相同键的字典列表转换为高数据框

Perl 包的 Python 等效项 (H*, $string)

python - 在 Python 中获取 ctypes 结构的二进制表示

当 rootfs 为只读且/tmp 为 noexec 时,Python ctypes 段错误

python - 如何使用 Flask 从 URL 获取命名参数?

Python unittest 传递参数

javascript - 如何为views.py中的对象创建属性,以便将更改后的对象传递给JS代码

python - 将元组的 Rust 向量转换为 C 兼容结构

python - Python 3.4 上的 GetProcAddress 奇怪行为

Python。类、结构、字典?