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コードを書き、gccMinGWでこれをコンパイルするために使用しました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");
    }
}

構造体には「2次元」配列が含まれていることに注意してください。

次に、次の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

私はPython2を使用しましたが、質問のタグはPython 3を使用していることを示しています。ただし、これで違いが生じるとは思いません。

于 2012-07-08T17:27:32.787 に答える