ctypes: reference of a struct member?

Günther Dietrich guenther.dietrich at spamfence.net
Fri May 1 18:28:45 EDT 2009


ma <mabdelkader at gmail.com> wrote:

>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



More information about the Python-list mailing list