4

我在 Python 代码和 C 代码中有结构。我填写这些字段

("bones_pos_vect",((c_float*4)*30)),
("bones_rot_quat",((c_float*4)*30))

在具有正确值的 python 代码中,但是当我在 C 代码中请求它们时,我从所有数组单元中只得到 0.0。为什么我会失去价值观?我的结构的所有其他领域都可以正常工作。

class SceneObject(Structure):
    _fields_ = [("x_coord", c_float),
                ("y_coord", c_float),
                ("z_coord", c_float),
                ("x_angle", c_float),
                ("y_angle", c_float),
                ("z_angle", c_float),
                ("indexes_count", c_int),
                ("vertices_buffer", c_uint),
                ("indexes_buffer", c_uint),
                ("texture_buffer", c_uint),
                ("bones_pos_vect",((c_float*4)*30)),
                ("bones_rot_quat",((c_float*4)*30))]

typedef struct
{
    float x_coord;
    float y_coord;
    float z_coord;
    float x_angle;
    float y_angle;
    float z_angle;
    int indexes_count;
    unsigned int vertices_buffer;
    unsigned int indexes_buffer;
    unsigned int texture_buffer;
    float bones_pos_vect[30][4];
    float bones_rot_quat[30][4];    
} SceneObject;
4

1 回答 1

14

这是一个如何将多维数组与 Python 和 ctypes 一起使用的示例。

我编写了以下 C 代码,并gcc在 MinGW 中用于将其编译为slib.dll

#include <stdio.h>

typedef struct TestStruct {
    int     a;
    float   array[30][4];
} TestStruct;

extern void print_struct(TestStruct *ts) {
    int i,j;
    for (j = 0; j < 30; ++j) {
        for (i = 0; i < 4; ++i) {
            printf("%g ", ts->array[j][i]);
        }
        printf("\n");
    }
}

请注意,该结构包含一个“二维”数组。

然后我编写了以下 Python 脚本:

from ctypes import *

class TestStruct(Structure):
    _fields_ = [("a", c_int),
                ("array", (c_float * 4) * 30)]

slib = CDLL("slib.dll")
slib.print_struct.argtypes = [POINTER(TestStruct)]
slib.print_struct.restype = None

t = TestStruct()

for i in range(30):
    for j in range(4):
        t.array[i][j] = i + 0.1*j

slib.print_struct(byref(t))

当我运行 Python 脚本时,它调用了 C 函数,该函数打印出多维数组的内容:

C:\>slib.py
0.1 0.2 0.3 0.4
1.1 1.2 1.3 1.4
2.1 2.2 2.3 2.4
3.1 3.2 3.3 3.4
4.1 4.2 4.3 4.4
5.1 5.2 5.3 5.4
... rest of output omitted

我使用过 Python 2,而您问题上的标签表明您正在使用 Python 3。但是,我认为这不会有所作为。

于 2012-07-08T17:27:32.787 回答