Python& Ctypes:读取作为参数传递的结构时的数据错误

时间:2015-02-02 17:14:14

标签: python c ctypes

我试图将ctypes结构传递给DLL。问题是DLL从结构中读取的数据是垃圾。这不是我在ctypes中实现的第一个结构,但它比我已经完成的其他结构更复杂。

结构定义如下:

typedef struct {
    double L, x, y;
} CieLxy;


typedef struct {
    int ledCur[3];
    CieLxy targetCie, modelCie, measuredCie;
} I1VpCal;


typedef struct {
    I1VpCal i1CalArray[8][7];
} I1CalArray;

使用以下测试功能:

int foo(I1CalArray* p_i1CalArray)
{
    int i, j;

    for (i=0; i<8; i++)
    {
        for (j=0; j<7; j++)
        {
            printf("in dll, i1CalArray[%d][%d].ledCur[0] = %d\n", 
                   i, j, p_i1CalArray->i1CalArray[i][j].ledCur[0]);
            printf("in dll, i1CalArray[%d][%d].measuredCie.L = %f\n", 
                   i, j, p_i1CalArray->i1CalArray[i][j].measuredCie.L);
        }    
    }
    return 0;
}

在Python中,我有以下ctypes定义:

class CieLxy(ctypes.Structure):
    _fields_ = [("L", ctypes.c_double),
                ("x", ctypes.c_double),
                ("y", ctypes.c_double)]


class I1VpCal(ctypes.Structure):
    _fields_ = [("ledCur", ctypes.c_int * 3),
                ("targetCie", CieLxy),
                ("modelCie", CieLxy),
                ("measuredCie", CieLxy)]


class I1CalArray(ctypes.Structure):
    _fields_ = [("i1CalArray", 8*(7*I1VpCal))]


Foo = Dll['foo']
# Foo.argtypes = [ctypes.POINTER(I1CalArray)]
Foo.argtypes = [ctypes.c_void_p]
Foo.restype = ctypes.c_int

def foo( i1CalArray):
#     p_i1CalArray = ctypes.POINTER(I1CalArray)
#     Foo(p_I1CalArray.from_address(ctypes.addressof(i1CalArray)))
#     Foo(i1CalArray)
    Foo(ctypes.byref(i1CalArray))

当我运行以下代码时:

i1CalArray_struct = I1CalArray()    
i1CalArray = i1CalArray_struct.i1CalArray

for i in range(8):
    for j in range(7):
        temp = i1CalArray[i][j].ledCur[0] = i+j
        temp = i1CalArray[i][j].measuredCie.L = float(i+j)

foo(i1CalArray_struct)

它打印的数据是垃圾。它看起来更像地址。

in dll, i1CalArray[0][0].ledCur[0] = 2620124
in dll, i1CalArray[0][0].measuredCie.L = -166230287672847070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
in dll, i1CalArray[0][1].ledCur[0] = 31662056
in dll, i1CalArray[0][1].measuredCie.L = 0.000000
in dll, i1CalArray[0][2].ledCur[0] = 36890704
in dll, i1CalArray[0][2].measuredCie.L = 0.000000
in dll, i1CalArray[0][3].ledCur[0] = 488321588
in dll, i1CalArray[0][3].measuredCie.L = 0.000000
in dll, i1CalArray[0][4].ledCur[0] = 0

对此的任何帮助都将非常感激。我已经阅读了很多帖子并尝试了不同的解决方案,但结果总是一样的。

使用Python 2.7,适用于Windows,Mac和Linux。 感谢

1 个答案:

答案 0 :(得分:1)

感谢评论,我能够看到错误。我没有正确使用byref变量。看评论。正确使用byref变量时,代码可以正常工作。


修改

根据评论中的要求,这是我最后使用的内容。

class I1CalArray(ctypes.Structure):
    _fields_ = [("i1CalArray", 8*(7*I1VpCal))]


Foo = Dll['foo']
Foo.argtypes = [ctypes.POINTER(I1CalArray)] 
def foo( i1CalArray):
    Foo(ctypes.byref(i1CalArray))   
    return i1CalArray