Question

I have a legacy C/C++ struct like this (with many other members as well):

struct S {
  char one_name[MAX_LEN];
  char names[N_NAMES][MAX_LEN];
}

and a C function that creates these:

S *get_S(...)

I'd like to export S and names via swig so I can do this in python:

s = MyModule.get_S()
print s.one_name # I have this working
print s.names[1] # should print the 2nd string, this is harder

I assume I need some kind of typemap but I'm new to swig. I can do one_name with the wrapped_array template as in SWIG/python array inside structure, but I'm not sure how to extend that to an array of strings. I only need to read these strings from python (as above), not write them. I can do it with an accessor so the python would look like:

print s.get_name(i) # prints the ith name

but I'd prefer the array interface just because it's similar to the C one.

Was it helpful?

Solution

If you only need to read them from python, then a quick solution is to create an adapter class that uses std::strings, and an adapter function. This all goes in the .i file via %inline, you'll also need %rename and probably %ignore. Example,

%ignore(S)
%rename(S) Swrap
%rename(get_S) get_SWrap
%newobject get_Swrap

%inline %{
struct Swrap
{
     inline Swrap(S* s): one_name(s.one_name) 
     {
          for (i=0; i<N_NAMES; ++i)
               names[i] = s.names[i];
          // no longer need s:
          delete s; 
     }

     string one_name;
     string names[N_NAMES];    
};

Swrap* get_Swrap() {
    return new Swrap(get_S());
}
%}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top