Python, ctypes, multi-Dimensional Array

前端 未结 1 2126
离开以前
离开以前 2020-12-15 14:53

I have structure in Python code and in C code. I fill these fields

(\"bones_pos_vect\",((c_float*4)*30)),
(\"bones_rot_quat\",((c_float*4)*30))
1条回答
  •  别那么骄傲
    2020-12-15 15:57

    Here's an example of how you can use a multidimensional array with Python and ctypes.

    I wrote the following C code, and used gcc in MinGW to compile this to slib.dll:

    #include 
    
    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");
        }
    }
    

    Note that the struct contains a 'two-dimensional' array.

    I then wrote the following Python script:

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

    When I ran the Python script, it called the C function, which printed out the contents of the multidimensional array:

    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
    

    I've used Python 2, whereas the tags on your question indicate that you're using Python 3. However, I don't believe this should make a difference.

    0 讨论(0)
提交回复
热议问题