2012-08-22 68 views
0

我有一個動態的C庫(比如foo.so),其中有具有以下原型如何用python ctypes處理wchar_t **?

wchar_t **foo(const char *); 

/* 
    The structure of the return value is a NULL terminated (wchar_t **), 
    each of which is also NULL terminated (wchar_t *) strings 
*/ 

現在我想用ctypes的模塊調用,通過從蟒蛇該API函數的函數

下面是我用試過片段:

from ctypes import * 

lib = CDLL("foo.so") 

text = c_char_p("a.bcd.ef") 
ret = POINTER(c_wchar_p) 
ret = lib.foo(text) 
print ret[0] 

但它顯示了以下錯誤:

Traceback (most recent call last):

File "./src/test.py", line 8, in

print ret[0]

TypeError: 'int' object has no attribute '_ _ getitem _ _'

任何有助於讓事情進入Python的東西是非常明顯的。

PS:我交的樣本ç代碼檢查FOO(「a.bcd.ef」)的功能& this是返回指針的樣子

回答

1

丟失的步驟是確定的fooargumentsreturn type

from ctypes import * 
from itertools import takewhile 

lib = CDLL("foo") 
lib.foo.restype = POINTER(c_wchar_p) 
lib.foo.argtypes = [c_char_p] 

ret = lib.foo('a.bcd.ef') 

# Iterate until None is found (equivalent to C NULL) 
for s in takewhile(lambda x: x is not None,ret): 
    print s 

簡單(Windows)中測試DLL:

#include <stdlib.h> 

__declspec(dllexport) wchar_t** foo(const char *x) 
{ 
    static wchar_t* y[] = {L"ABC",L"DEF",L"GHI",NULL}; 
    return &y[0]; 
} 

輸出:

ABC 
DEF 
GHI