[cython-users] How to wrap C function taking int* ?

13 views
Skip to first unread message

Jeff

unread,
May 18, 2010, 12:35:59 PM5/18/10
to cython-users
I'd like to wrap a C library using Cython but I can't find any simple
documentation to do exactly what I need. I have many functions to
wrap of the form:

/* header.h */
void somefunc(int type, int length, int *dims, char *name, int *foo);

I'd like to expose that function to Python while allowing the int
arrays to be Python lists, tuples, numpy arrays, or any combination
thereof. Please note the last int array could also be NULL and the
length argument refers to the length of the dims and foo arrays.

Can somebody show me how this is done? Thanks.

Jeff

Robert Bradshaw

unread,
May 18, 2010, 12:51:14 PM5/18/10
to cython...@googlegroups.com
You need to convert the list into a (manually) allocated int*
yourself. For example,

from libc.stdlib cimport malloc, free # or "from stdlib..."

def somefunc_py(int type, dims, char *name, foo):
cdef int *dims_c = NULL, *foo_c = NULL
try:
dims_c = malloc(sizeof(int) * len(dims))
if dims_c == NULL:
raise MemoryError
for i, a in enumerate(dims):
dims_c[i] = a
foo_c = malloc(sizeof(int) * len(foo))
if foo_c == NULL:
raise MemoryError

for i, a in enumerate(foo):
foo_c[i] = a
somefunc(type, len(dims), dims_c, name, foo_c)
finally:
if dims_c != NULL:
free(dims_c)
if foo != NULL:
free(foo)

You could factor some of this out to a utility function if you're
going to use it a lot. I'm completely ignoring the fat that you may
want to do some encoding/decoding for your char*, and/or check the
dimensions for dims and foo for compatibility.

This is certainly something we would like to make more natural.

- Robert

Reply all
Reply to author
Forward
0 new messages