-2

I have a fairly simple C routine I would like to access via Python, using SWIG:

int routine(char *instring, char *outstring);

The input string is just passed in, and that seems to work. The outstring return is a pointer to a fixed array within the C routine, and my problem is how to pass a python parameter to it using the python interface.

When I use python, I get:

>>retstring = "foo"
>>retval = routine("Hello world", retstring)

This (obviously) doesn't work because the value is lost when the scope returns to the prompt level. But the routine doesn't fail. The problem is, any OTHER parameter I pass in fails because it is not considered a char *.

Other than not returning the string, the routine seems to be working.

I'm not sure what to do. Do I have to modify with typemaps to produce a second return? Is there an example somewhere that shows this?

Jiminion
  • 5,080
  • 1
  • 31
  • 54
  • Possible duplicate of [ctypes return a string from c function](http://stackoverflow.com/questions/14883853/ctypes-return-a-string-from-c-function) – LPs May 17 '16 at 15:34
  • You need to tell us a little more about `routine` for it to be possible to answer this: how do you know how large to make the allocation for `outstring`? Typically either the return value as in tells you how big to make it if `oustring` is null, or there's a fix bound on the size, but it could also depend on the input in `instring` or any other scheme is possible. – Flexo May 17 '16 at 21:13
  • @Flexo : I don't have to allocate outstring. It is preallocated (statically) within the routine (yes, not good from a threading standpoint). I'm looking toward cstring.i as SWIG seems pretty leery of dealing with C strings. Or carrays.i, but SWIG says not to use them for chars. – Jiminion May 17 '16 at 21:18
  • Is it `char** outstring` then? Because if it's statically allocated then you won't be able to return it with the function arguments you showed. The answer you posted looks like it's fixed 1024 bytes though, so still no clearer. – Flexo May 17 '16 at 21:58
  • It is a static (fixed length) string within the routine. Just the pointer to it is returned, containing the answer. – Jiminion May 17 '16 at 22:28

1 Answers1

0

Okay, I got it to work like this (.i file):

%module example
%include cstring.i
%cstring_bounded_output(char *outcs, 1024);  // large magic number...
%{
#include "routine.h"
%}

int routine(char *instring, char *outcs);

The call is then (in Python):

import example
retval, restring = example.routine("Hello World")
Jiminion
  • 5,080
  • 1
  • 31
  • 54