2016-07-19 27 views
1
values = ffi.new("int[]", 10) 
pValue = ffi.addressof(pInt, 0) 

使用Python CFFI使用Python CFFI(C * - 運算符等效?)ffi.addressof創建的指針,上面的代碼創建的指針的values作爲pValue第一要素。解引用

然後,您可以使用values[ 0 ]訪問其內容,但這不是真正透明的,並且有時不方便跟蹤哪些指標具有什麼價值。

是否有任何東西如C *-operator,一個函數或其他東西來取消引用pValue並直接訪問其內容?

在其他語言...:

// In C: 
// ===== 

int values[ 10 ] = {0}; 
int* pValue = &(values[ 0 ]); 

func_with_pointer_to_int_as_param(pValue); 

printf("%d\n", *pValue); 

------------------------------------------------------------- 

# In Python with CFFI: 
# ==================== 

values = ffi.new("int[]", 10) 
pValue = ffi.addressof(values, 0) 

lib.func_with_pointer_to_int_as_param(pValue) #lib is where the C functions are 

print values[ 0 ] #Something else than that? Sort of "ffi.contentof(pValue)"? 

編輯:
下面是一個使用情況下是有用的:

我覺得它更具可讀性的事:

pC_int = ffi.new("int[]", 2) 
pType = ffi.addressof(pC_int, 0) 
pValue = ffi.addressof(pC_int, 1) 
... 

# That you access with: 
print "Type: {0}, value: {1}".format(pC_int[ 0 ], pC_int[ 1 ]) 

而不是:

pInt_type = ffi.new("int[]", 1) 
pType  = ffi.addressof(pInt_type, 0) 

pInt_value = ffi.new("int[]", 1) 
pValue  = ffi.addressof(pInt_value, 0) 

... 

# That you access with: 
print "Type: {0}, value: {1}".format(pInt_type[ 0 ], pInt_value[ 0 ]) 

我想前者更快。但是,當您想要訪問這些值時,它會使您不便於記憶,如「ok類型爲數字0」等...

+1

在C中,'* x'是完全等效於'X [0]'。 –

+0

是的。我添加了一個用例,它有一個直接取消引用CData的指針是有用的。 – DRz

+1

對不起,我還是不明白。你想幹什麼?那是你用C編寫的'* pType','* pValue'嗎?然後你可以寫它'pType [0]','pValue [0]'。當然你也可以定義和使用你自己的函數def contentof(p):return p [0]'。 –

回答

1

在C中,語法*pType總是等於pType[0]。所以說你想做類似的事情:

print "Type: {0}, value: {1}".format(*pType, *pValue) 

但當然這是無效的Python語法。該解決方案是,可以隨時重寫它像這樣,成爲有效的Python語法:

print "Type: {0}, value: {1}".format(pType[0], pValue[0])