2017-08-24 38 views
0

以下是C函數para_trans_test如何使用ctypes將字符串數組從python傳遞到C並修改C中的數組值

void para_trans_test(char x [] [100]) 
{ 
    strncpy(x[0],"zzz",100); 
} 

以下是不起作用的python代碼。

lib.para_trans_test.argtypes= [ctypes.POINTER(ctypes.c_char_p)] 
numParams=2 
L=numpy.array(['xxx','yyy']) 
print(type(L)) 
py_s1 = (ctypes.c_char_p * numParams)() 
py_s1[:]=L 
print("py_s1=",py_s1) 
lib.para_trans_test(py_s1) 
print(py_s1) 

最初數組L是('xxx','yyy')。

調用C函數para_trans_test我想排列L是( 'ZZZ', 'YYY')

+1

不工作*如何* ? –

回答

1

後參數類型是錯誤的。 POINTER(c_char_p)相當於char**。我們需要的是一個指針數組c_char

測試DLL:

#include <string.h> 
__declspec(dllexport) void para_trans_test(char x [] [100]) 
{ 
    strncpy(x[0],"zzz",100); 
} 

的Python:

from ctypes import * 
lib = CDLL('test') 
lib.para_trans_test.argtypes = [POINTER(c_char * 100)] 
py_s1 = (c_char * 100 * 2)() 
py_s1[0].value = b'xxx' 
py_s1[1].value = b'yyy' 
print(py_s1[0].value,py_s1[1].value) 
lib.para_trans_test(py_s1) 
print(py_s1[0].value,py_s1[1].value) 

輸出:

b'xxx' b'yyy' 
b'zzz' b'yyy' 
相關問題