Accessing a structure element in Python

Question:

I’m having trouble accessing a structure element. Notice that I have read something into the structure using
sscanf (to simulate my actual routine) but Python does not seem to realize that. So I added a statement
to assign a value, then Python realizes there is something there. This only happens when I’m reading into a
strcuture … as I have read into a c_ulong and that works just fine.

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
Asked By: Eddy

||

Answers:

You are printing the class variable not the instance variable (note the case):

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

Output:

<Field type=c_ulong, ofs=0, size=4>
1
Answered By: Mark Tolonen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.