我在 Python 代码和 C 代码中都有结构。我填写这些字段
("bones_pos_vect",((c_float*4)*30)),
("bones_rot_quat",((c_float*4)*30))
在具有正确值的 python 代码中,但是当我在 C 代码中请求它们时,我从所有数组单元格中只得到 0.0。为什么我会失去值(value)?我的结构的所有其他字段都工作正常。
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;
最佳答案
这是一个示例,说明如何将多维数组与 Python 和 ctypes 一起使用。
我编写了以下 C 代码,并使用 MinGW 中的 gcc
将其编译为 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。但是,我认为这不会有什么不同。
关于Python,ctypes,多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11384015/