jtlz2
jtlz2

Reputation: 8407

ctypes: extract members of structure returned by C library

I am trying to use ctypes to extract a structure initialized by a C library (see for example: https://tentacles666.wordpress.com/2012/01/21/python-ctypes-dereferencing-a-pointer-to-a-c).

The 'prototype' is:

mytype * createMyType();

The structure in C is:

typedef struct
{
        int              a;
        void             *b;
}mytype;

from which in python(3)! I have created a ctypes structure thus:

class mytype(ctypes.Structure):
    _fields_ = [("a", ctypes.c_int),
               ("b", ctypes.POINTER(None))]

The C call is:

mytype*myinstance = createMyType()

The Python call is as follows:

import ctypes
f=mylib.createMyType
f.argtypes=()
f.restype=(ctypes.POINTER(mytype),)
x=f()

The problem is that x seems to be an integer; how do I interpret this as a pointer, or - as required - extract the members of x themselves?

How do I access and then modify x.a and x.b?

[See also Accessing data from a structure returned by C function in Python using ctypes, which led nowhere]

Upvotes: 1

Views: 1612

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177685

Mainly you need c_void_p for the void* and must dereference the return with .contents.

Here's a working example (Windows)...

Edit: I added an example of casting the void pointer member.

test.h

#ifdef EXPORT
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

typedef struct
{
        int a;
        void* b;
} mytype;

API mytype* createMyType();
API void destroyMyType(mytype* p);

test.c

#define EXPORT
#include <stdlib.h>
#include <stdio.h>
#include "test.h"

API mytype* createMyType()
{
    int* tmp;
    mytype* p = malloc(sizeof(mytype));
    p->a = 5;
    tmp = malloc(sizeof(int));
    *tmp = 123;
    p->b = tmp;
    printf("%d %p\n",p->a,p->b);
    return p;
}

API void destroyMyType(mytype* p)
{
    free(p->b);
    free(p);
}

test.py

from ctypes import *

class mytype(Structure):
    _fields_ = [('a',c_int),
                ('b',c_void_p)]

test = CDLL('test')
createMyType = test.createMyType
createMyType.argtypes = None
createMyType.restype = POINTER(mytype)
destroyMyType = test.destroyMyType
destroyMyType.argtypes = POINTER(mytype),
destroyMyType.restype = None

t = createMyType()
print('t is',t)
print('t.a is',t.contents.a)
print('t.b is',hex(t.contents.b))
b = cast(t.contents.b,POINTER(c_int))
print('*b is',b.contents)
destroyMyType(t)

Output: Note that the void* b address output in the C code matches the integer returned by t.contents.b. The cast turns that integer into a POINTER(c_int) where the contents can be extracted.

5 00000216C0E2A5D0
t is <__main__.LP_mytype object at 0x00000216C30C4A48>
t.a is 5
t.b is 0x216c0e2a5d0
*b is c_long(123)

Upvotes: 2

Related Questions