2010-11-04 199 views
5

我試圖將字符數組數組傳遞給使用ctypes的C函數。python ctypes中的多維char數組(字符串數組)

void cfunction(char ** strings) 
{ 
strings[1] = "bad"; //works not what I need. 
strings[1][2] = 'd'; //this will segfault. 
return; 
} 

char *input[] = {"foo","bar"}; 
cfunction(input); 

因爲我到處亂扔陣列靜態反正定義, 我只是改變了函數的聲明和輸入參數,像這樣:

void cfunction(char strings[2][4]) 
{ 
//strings[1] = "bad"; //not what I need. 
strings[1][2] = 'd'; //what I need and now it works. 
return; 
} 

char input[2][4] = {"foo","bar"}; 
cfunction(input); 

現在我遇到的如何界定這個問題python中的多維字符 數組。我以爲它會這樣:

import os 
from ctypes import * 
libhello = cdll.LoadLibrary(os.getcwd() + '/libhello.so') 
input = (c_char_p * 2)() 
input[0] = create_string_buffer("foo") 
input[1] = create_string_buffer("bar") 
libhello.cfunction(input) 

這給我TypeError: incompatible types, c_char_Array_4 instance instead of c_char_p instance。如果我將其更改爲:

for i in input: 
i = create_string_buffer("foo") 

然後我得到分段錯誤。另外這個貌似錯誤的方式來構建二維數組,因爲如果我打印輸入我看到None

print input[0] 
print input[1] 

# outputs None, None instead of "foo" and "foo" 

我也碰到使用#DEFINE MY_ARRAY_X 2#DEFINE MY_ARRAY_Y 4保持陣列尺寸直在我的C​​文件的問題,但不知道從libhello.so中獲取這些常量的好方法,以便python在構造數據類型時可以引用它們。

+0

@這一個user17925任何反饋? – 2010-11-06 10:17:14

+0

@Purcaru看起來不錯;我把你的構建工作放到了我的代碼中,它工作正常python文檔提供了create_string_buffer幫助函數,所以我想我只是決定使用它。 – user17925 2010-11-08 00:35:24

回答

9

使用類似

input = ((c_char * 4) * 2)() 
input[0].value = "str" 
input[0][0] == "s" 
input[0][1] == "t" # and so on... 

簡單的用法:

>>> a =((c_char * 4) * 2)() 
>>> a 
<__main__.c_char_Array_4_Array_2 object at 0x9348d1c> 
>>> a[0] 
<__main__.c_char_Array_4 object at 0x9348c8c> 
>>> a[0].raw 
'\x00\x00\x00\x00' 
>>> a[0].value 
'' 
>>> a[0].value = "str" 
>>> a[0] 
<__main__.c_char_Array_4 object at 0x9348c8c> 
>>> a[0].value 
'str' 
>>> a[0].raw 
'str\x00' 
>>> a[1].value 
'' 
>>> a[0][0] 
's' 
>>> a[0][0] = 'x' 
>>> a[0].value 
'xtr' 
+0

謝謝。這真是太棒了! – Ajoy 2013-03-03 15:29:10