I am trying to use a C library in Python using SWIG. This C library passes function results through arguments everywhere. Using the online SWIG manual, I have succeeded in getting an integer function result passed to Python, but I am having a hard time figuring out how to do this for a character string.
This is the essence of my code:
myfunc.c :
#include <myfunc.h>
#include <stdio.h>
int mystr(int inp, char *outstr){
outstr="aaa";
printf("%s\n", outstr);
return(0);
}
myfunc.h :
extern int mystr(int inp, char *outstr);
So basically my question is what the typemap for *outstr should look like.
Thanks in advance.
Have a look at the SWIG manual 9.3.4 String handling: cstring.i . This provides several typemaps for use with char *
arguments.
Probably (assuming you are indeed using strcpy(outstr, "aaa")
as mentioned in a comment above) you want in your SWIG interface file, before the function declaration, eg:
%include <cstring.i>
%cstring_bounded_output(char* outstr, 1024);
This is how I got it to work, by modifying the example in section 34.9.3 of the SWIG 2.0 manual :
%typemap(in, numinputs=0) char *outstr (char temp) {
$1 = &temp;
}
%typemap(argout) char *outstr {
PyObject *o, *o2, *o3;
o = PyString_FromString($1);
if ((!$result) || ($result == Py_None)) {
$result = o;
} else {
if (!PyTuple_Check($result)) {
PyObject *o2 = $result;
$result = PyTuple_New(1);
PyTuple_SetItem($result,0,o2);
}
o3 = PyTuple_New(1);
PyTuple_SetItem(o3,0,o);
o2 = $result;
$result = PySequence_Concat(o2,o3);
Py_DECREF(o2);
Py_DECREF(o3);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.