From: William S F. <ws...@fu...> - 2013-10-21 19:55:02
|
On 19/10/13 11:21, Stefan Bellon wrote: > Hi all, > > I'm interfacing C and Python 2.7 using SWIG 2.0.x. Previously I've only > been using char* and const char* to create the mapping to the C side, > but now I'd like to use C++ and directly interface std::string& as well. > > I have the convention that on the C/C++ side strings are internally > represented in UTF-8 encoding. Therefore my Typemap for the pure C side > currently looks like this: > > %typemap(in) const char * (PyObject *temp_obj = NULL), > char * (PyObject *temp_obj = NULL) > { > // Python -> C > if (PyString_Check($input)) > { > $1 = PyString_AsString($input); > } > else if (PyUnicode_Check($input)) > { > temp_obj = PyUnicode_AsUTF8String($input); > if (temp_obj != NULL) > { > $1 = PyString_AsString(temp_obj); > } > else > { > SWIG_exception_fail(SWIG_RuntimeError, > "in method '$symname', > argument '$1_name' corrupt unicode"); > } > } > else > { > SWIG_exception_fail(SWIG_TypeError, > "in method '$symname', > argument '$1_name' of type '$1_type'"); > } > } > > (Not sure, perhaps this can be even simplified, but it works.) > > However I am completely unsure of how to extend this to work with C++ > std::string as well. > > At present, I have > > %include "std_string.i" > %include "std_wstring.i" > > in my .i file, and it works for Python "str", but not for "unicode": > > TypeError: in method 'test', argument 1 of type 'std::string' > > Any help of how to get Python 2.7 "unicode" to C++ std::string using > UTF-8 encoding would be greatly appreciated! You'll probably need to redefine all the std::string typemaps. This can be a bit mind boggling as the implementation is hidden behind a number of macros. I suggest using the preprocessor by running swig -E and looking for the std::string typemaps and then provide your own overrides. Probably you just need the 'in', 'out' typemaps for std::string and const std::string&, but it really depends on what you are using. William |