I have a makeshift C library with which I want to access using python. The problem is that the code consists essentially of two parts, initialization for reading in data from several files and several calculations that need to be performed only once. The other part is called in a loop and uses the data generated earlier several times. To this function, I want to pass parameters from python.
My idea was to write two C shell functions, "init" and "loop" - "init" reads the data and returns a void pointer to a structure that loop can use along with additional parameters that I can pass from python . Sort of
void *init() { struct *mystruct ret = (mystruct *)malloc(sizeof(mystruct)); return ret; } float loop(void *data, float par1, float par2) { }
I tried calling init from python as c_void_p, but since the loop changes part of the contents of the data and the void void pointers are immutable, this did not work.
Other solutions to similar problems that I have seen seem to require knowing how much memory "init" will use, and I don't know that.
Is there a way to pass data from one C function to another via python without telling python exactly what and how it is? Or is there another way to solve my problem?
I tried (and could not) write a minimal emergency example, and after some debugging it turned out that there was an error in my C code. Thanks to all who responded! Hoping this can help other people, here is something like a minimal working version (still without a separate βfreeβ - sorry):
pybug.c:
#include <stdio.h> #include <stdlib.h> typedef struct inner_struct_s { int length; float *array; } inner_struct_t; typedef struct mystruct_S { int id; float start; float end; inner_struct_t *inner; } mystruct_t; void init(void **data) { int i; mystruct_t *mystruct = (mystruct_t *)malloc(sizeof(mystruct_t)); inner_struct_t *inner = (inner_struct_t *)malloc(sizeof(inner_struct_t)); inner->length = 10; inner->array = calloc(inner->length, sizeof(float)); for (i=0; i<inner->length; i++) inner->array[i] = 2*i; mystruct->id = 0; mystruct->start = 0; mystruct->end = inner->length; mystruct->inner = inner; *data = mystruct; } float loop(void *data, float par1, float par2, int newsize) { mystruct_t *str = data; inner_struct_t *inner = str->inner; int i; inner->length = newsize; inner->array = realloc(inner->array, newsize * sizeof(float)); for (i=0; i<inner->length; i++) inner->array[i] = par1 + i * par2; return inner->array[inner->length-1]; }
compile as
cc -c -fPIC pybug.c cc -shared -o libbug.so pybug.o
Running in python:
from ctypes import * sl = CDLL('libbug.so')