2017-06-22 73 views
1

我第一次使用python ctypes。我的目的是將一個python列表轉換成一個位於ctype union內部的數組。但是,當我嘗試這樣做時,我得到TypeError。我粘貼了下面的代碼,因爲我無法找到適合此場景的示例: 請發表評論。在ctypes union中訪問數組

from ctypes import * 
class state_struct(Structure): 
    _fields_ = [ 
       ("loc0", c_uint32 * 3), 
       ("loc1", c_uint32), 
       ("loc2", c_uint32 * 12), 
       ("loc3", c_uint32 * 28), 
       ("loc4", c_uint32 * 2), 
       ] 

class state_union(Union): 
    _fields_ = [("state_struct", state_struct), 
       ("data", c_uint32 * 46), 

       ] 
def populate_union(): 
    u = state_union() 
    l = [1,2,3] 
    for i in iter(l): 
     u.state_struct.loc0 = i 


populate_union() 

類型錯誤:預期c_uint_Array_3情況下,得到了INT

回答

1

state_struct.loc0是一個長度爲3的數組,如果你想爲整數分配給他們你需要索引其內容。

例如:

l = [1,2,3] 
for index, value in enumerate(l): 
    u.state_struct.loc0[index] = value 

,或者你可以用切片索引一氣呵成分配整個列表:

u.state_struct.loc0[:] = l