SWIG Question

Randall Hopper aa8vb at yahoo.com
Fri Oct 15 06:30:07 EDT 1999


frankmcgeough at my-deja.com:
 |
 |I am a SWIG newbie. It looks pretty cool. I was able to download it
 |today and get basic stuff working in a couple hours.

Yeah.  It's certainly a useful tool.

 |Question: I have a number of C++ classes that have string members that
 |are returned by get methods.
 |
 |ex: std::string getErrorString();
 |
 |SWIG maps this to a string representing a pointer by default. I'd like
 |to do a .c_str() and convert the value to a Python string. How do I
 |setup a typemap to do this?

I've only wrapped C with Python, but I'd guess you want to look at using
%addmethods to add a function to your class to access your string as a char
* (or just add one to your C API).  SWIG will wrap this such that it is
accessible as a Python string.  So there's no need to use any
Python-specific code in the wrappers.

Possibly something like this, though you'll want to do something more
intelligent with the size and location of the returned string buffer:

     %addmethods MY_STRING
     {
       const char *GetCString()
       {
          static  char result[80];

          result[0] = '\0';
          stncat( result, internal_str, sizeof(result)-1 )
          return result;
       }
     }

Randall




More information about the Python-list mailing list