0

我有一个动态 C 库(比如foo.so),其中有一个具有以下原型的函数

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模块从 python 通过这个 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]

但它显示以下错误:

回溯(最近一次通话最后):

文件“./src/test.py”,第 8 行,在

打印 ret[0]

TypeError:“int”对象没有属性“_ _ getitem _ _”

任何帮助在 python 中进行的事情都是非常明显的。

PS:我已经在示例C代码中交叉检查了 foo("a.bcd.ef") 的功能,就是返回指针的样子

4

1 回答 1

3

缺少的步骤是定义参数返回foo类型:

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
于 2012-08-23T02:05:21.407 回答