如何修复RaspberryPi中的'ctypes.ArgumentError:参数2:<type'exceptions.TypeError'>:错误的类型'错误

时间:2019-09-17 13:11:00

标签: python c++ ctypes

我想创建一个C ++库(.so)并在Python中使用它。 但是如您所见,C ++函数参数是固定大小的数组。 如下所示创建python源时, lib.ShiftRows.argypes = types.c_void_p,?] 我应该在“”中输入什么类型的数据?部分?

在实际使用上述类时,Python如何声明一个数组以声明与c ++相同的数组变量?

AES.cpp:

void AESS::ShiftRows( char state[0x04][0x04]) {
int i, j, k, tmp;

for (i = 0; i<4; i++) {
    for (j = 4 - i; j<4; j++) {
        tmp = state[i][0];
        for (k = 0; k<4 - 1; k++) {
            state[i][k] = state[i][k + 1];
        }
        state[i][3] = tmp;
    }
  }
}

extern "C"
{
    AESS* AESS_new(){return new AESS();}
    void ShiftRows(AESS* aes,  char state[0x04][0x04]) {aes->ShiftRows(state);}
}

AESClass.py:

import ctypes

lib = ctypes.cdll.LoadLibrary('./libAESS.so')

class AESS():
    def __init__(self):
        lib.AESS_new.argtypes = []
        lib.AESS_new.restype = ctypes.c_void_p        

        lib.ShiftRows.argtypes=[ctypes.c_void_p , ?]
        lib.ShiftRows.restype= ctypes.c_void_p

        self.obj=lib.AESS_new()

    def ShiftRows(self, state):
        lib.ShiftRows(self.obj, state)

AES.py:

import numpy as np
from AESClass import AESS

state = np.zeros((4,4))

aes = AESS()

aes.ShiftRows(state)

1 个答案:

答案 0 :(得分:0)

签出[Python 3.Docs]: ctypes - A foreign function library for Python数组部分)。

您可以执行以下操作:

  • AESClass.py

    CharArr4 = ctypes.c_char * 4
    CharArr4Arr4 = CharArr4 * 4
    
    class AESS():
    
    # ...
    
            lib.ShiftRows.argtypes = [ctypes.c_void_p , CharArr4Arr4]
    
  • AES.py (使用[SciPy]: numpy.ctypeslib.as_array(obj, shape=None)):

    import numpy as np
    from AESClass import AESS, CharArr4Arr4
    
    
    state_arr = CharArr4Arr4()  # Initialize the 4 X 4 array to 0
    aes = AESS()
    aes.ShiftRows(state_arr)
    
    state = np.ctypeslib.as_array(state_arr)
    

    或相反:

    # ...
    state = np.zeros((4, 4), dtype=np.int8)
    # ...
    aes.ShiftRows(np.ctypeslib.as_ctypes(state))