C code: uses fractal_create() to assign a 2D array to 'values' array in the struct fractal_t
//2D.c
#include <stdlib.h>
#include <stdio.h>
typedef struct
{
size_t height;
size_t width;
double values[];
} fractal_t;
void fractal_destroy (fractal_t* f)
{
free(f);
}
void fractal_fill (fractal_t* f)
{
double (*array_2D)[f->width] = (double(*)[f->width]) f->values;
for (size_t height=0; height < f->height; height++)
{
for (size_t width=0; width < f->width; width++)
{
array_2D[height][width] = width; // whatever value that makes sense
}
}
}
void fractal_print (const fractal_t* f)
{
double (*array_2D)[f->width] = (double(*)[f->width]) f->values;
for(size_t height=0; height < f->height; height++)
{
for(size_t width=0; width < f->width; width++)
{
printf("%.5f ", array_2D[height][width]);
}
printf("\n");
}
}
fractal_t* fractal_create (size_t height, size_t width)
{
// using calloc since it conveniently fills everything with zeroes
fractal_t* f = calloc(1, sizeof *f + sizeof(double[height][width]) );
f->height = height;
f->width = width;
// ...
fractal_fill(f); // fill with some garbage value
fractal_print(f);
return f;
}
int main (void)
{
int h = 3;
int w = 4;
fractal_t* fractal = fractal_create(h, w);
fractal_destroy(fractal);
}
I'm trying to access this 'values' 2D array from python using ctypes
python code:
from ctypes import *
h = 3
w = 4
class fractal_t(Structure):
_fields_ = [("a", c_int),
("values", (c_double * h) * w)]
slib = cdll.LoadLibrary('/2D.so')
t = fractal_t
fun = slib.fractal_create
t = fun(c_int(h),
c_int(w))
p1 = fractal_t.from_address(t)
print(p1.values[0][0])
print(p1.values[0][1])
print(p1.values[0][2])
for i in p1.values:
print(i, end=" \n")
for j in i:
print(j, end=" \n")
output:
0.00000 1.00000 2.00000 3.00000
0.00000 1.00000 2.00000 3.00000
0.00000 1.00000 2.00000 3.00000
2e-323
0.0
1.0
<__main__.c_double_Array_3 object at 0x7f5c7836f8c8>
2e-323
0.0
1.0
<__main__.c_double_Array_3 object at 0x7f5c7836fb70>
2.0
3.0
0.0
<__main__.c_double_Array_3 object at 0x7f5c7836f8c8>
1.0
2.0
3.0
<__main__.c_double_Array_3 object at 0x7f5c7836fb70>
0.0
1.0
2.0
The first 3 lines from the output is printed from fractal_print()in C. When i tried to access the 2D array using p1.values[0][0], I'm not getting the correct value. Not sure what is wrong here.