簡體   English   中英

python ctypes中的多維char數組(字符串數組)

[英]Multi-dimensional char array (array of strings) in python ctypes

我正在嘗試使用ctypes將一個字符數組數組傳遞給C函數。

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可以在構造數據類型時引用它們。

使用類似的東西

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM