I am trying to learn to use ctypes to populate a linked list of C structs and return the head of the list to Python for post processing. To do that, I have a simple C struct, defined like so:
struct Checkpoint
{
double *state;
struct Checkpoint *next;
};
typedef struct Checkpoint checkpoint;
And I have a simple matching Python 3 class defined like so:
class Checkpoint(ct.Structure):
pass
Checkpoint._fields_ = [('state', ct.POINTER(ct.c_double)),
('next', ct.POINTER(Checkpoint))]
After calling the C code via ctypes to populate a few examples of this structure, I try to print the values in the state array on the python side.
def main():
# Load the shared library into c types.
libc = ct.CDLL("./structs.so")
entry = wrap_function(libc, 'pymain', ct.POINTER(Checkpoint), None)
get_state = wrap_function(libc, 'get_state', ct.POINTER(ct.c_double), [ct.POINTER(Checkpoint)])
get_next = wrap_function(libc, 'get_next', ct.POINTER(Checkpoint), [ct.POINTER(Checkpoint)])
start = entry()
print(get_state(start).contents);
start = get_next(start)
print(get_state(start).contents);
The get_state and get_next functions are as follows:
double *get_state(checkpoint *current)
{
return current->state;
}
checkpoint *get_next(checkpoint *current)
{
return current->next;
}
These functions are returning a reference to the correct memory, but I am having trouble accessing anything beyond the first element of the arrays in the structs so defined.
Two questions:
Do I need the
get_stateandget_nextfunctions, or can I access those parameters directly in Python without doing a call back to C after my structures are defined and populated? If so, how?My
mainfunction in python works to populate the structures as I want them, but only the first value of thestatearray is printed by theprintcalls. How to I access the rest of the values in the array?