Question

I've a dynamic C library (say foo.so) in which there's a function having the following prototype

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
*/

Now I want to call the function through this API from python using ctypes module

Here's the snippet I've tried with :

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]

But it's showing the following error :

Traceback (most recent call last):

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

print ret[0]

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

Any help to get things going in python is keenly appreciable.

P.S : I've cross checked the functionality of foo("a.bcd.ef") in a sample C code & this is what the return pointer looks like

Was it helpful?

Solution

The missing steps are to define the arguments and return type of 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

Simple (Windows) test 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];
}

Output:

ABC
DEF
GHI
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top