jacobra
jacobra

Reputation: 2152

Calling a C function from Python generated by SWIG, with char * output

I'm new to SWIG and if my question is documented, feel free to just post the link and I'll read through it.

I have a C function that takes the form:

int myFunc(char *output, const char *input)

I generated the Python wrapper, and I tried calling this function (in Python) with:

m=""
n="valid input string"
myFunc(m,n)

This simply prints the (int) return code, and m is still "". What am I doing wrong?

Thanks!

Upvotes: 1

Views: 1044

Answers (2)

Oktalist
Oktalist

Reputation: 14724

From the SWIG manual section 8.3.4:

If your C function is declared like this:

int myFunc(char *myOutput, const char *myInput);

Then you can use the following SWIG interface syntax:

%include "cstring.i"

%cstring_bounded_output(char *myOutput, 1024);

int myFunc(char *myOutput, const char *myInput);

This should result in a Python wrapper function taking a single string argument (myInput) and returning a tuple of an integer (the C function's return value) and a string (myOutput). Memory for the string will be allocated by SWIG and be 1024 bytes in length, in this example.

Upvotes: 1

Markku K.
Markku K.

Reputation: 3908

OK, it is not recommended practice (see my comment), and YMMV, but this seems to work for me with Python 2.4:

#pre-allocate enough space for m
m = "\x00"*100
n = "valid input string"
myFunc(m,n)
# now m.rstrip("\x00") has what you want

Upvotes: 0

Related Questions