[使用ctypes在python中访问C结构中的2D数组

问题描述 投票:1回答:1

C代码:使用fractal_create()将2D数组分配给struct fractal_t中的'values'数组

//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);
}

我正在尝试使用ctypes从python访问此'values'二维数组

python代码:

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])

输出:

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

输出的前3行是从C中的fractal_print()打印的。当我尝试使用p1.values [0] [0]访问2D数组时,我没有得到正确的值。不知道这里出了什么问题。

python c ctypes
1个回答
0
投票
typedef struct 
{
    size_t height;
    size_t width;
    double values[];
} fractal_t;
© www.soinside.com 2019 - 2024. All rights reserved.