ctypes: reference of a struct member?

M

ma

If I have this struct in C:

struct spam {
int ham;
char foo;
};


if I have this declaration:
struct spam s_;

If I wanted to pass a reference to a function of s_'s foo character, I
can do something like this:

somefunc(&s_.foo)

How do I do the same thing in ctypes?
ctypes.addressof(s_) + ctypes.sizeof(spam.foo)*(1)
 
M

ma

ctypes.byref() does not work for struct members.
Try it out.
class s(ctypes.Structure):
_fields_ = [('x',ctypes.c_int)]

a = s()
ctypes.byref(a.x) //this won't work.
 
G

Günther Dietrich

ma said:
If I have this struct in C:

struct spam {
int ham;
char foo;
};


if I have this declaration:
struct spam s_;

If I wanted to pass a reference to a function of s_'s foo character, I
can do something like this:

somefunc(&s_.foo)

How do I do the same thing in ctypes?
ctypes.addressof(s_) + ctypes.sizeof(spam.foo)*(1)

See ctypes.create_string_buffer().
To unpack the struct elements received from the C function, use
struct.unpack().

Here some example:

def rssiam_volt_Q(self):
'''Output Voltage Query
'''
query_buffer = ctypes.create_string_buffer(8)
self.rssiam_32_dll.rssiam_volt_Q.argtypes = [ctypes.c_long,
ctypes.c_char_p]
result = self.rssiam_32_dll.rssiam_volt_Q(self.session,
query_buffer)
if result != VI_SUCCESS:
raise IOError, 'rssiam_volt_Q: result = %d' % result
return(struct.unpack('d', query_buffer.raw)[0])


In this case, it is a 64 bits float (= double) value that is returned by
reference (query_buffer).
Attention, struct.unpack() returns a tuple, even when there is only a
single element to extract from the buffer.




Regards,

Günther
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top