Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make SWIG return unicode objects for strings in Python 2?

I have something like the following:

swigtest.cpp

#include <string>

class Foo {
public:
    std::string bar() {
        return "baz";
    }
};

inline Foo* new_foo() {
    return new Foo;
}

swigtest.i

%module swigtest
%{
#include "swigtest.hpp"
%}

%include <std_string.i>
%include "swigtest.hpp"

%newobject new_foo;

useswig.py

from swigtest import new_foo

foo = new_foo()
print(foo.bar())
print(type(foo.bar()))
$ swig -c++ -python -modern swigtest.i
$ g++ -fpic -shared -I/usr/include/python2.7 -DSWIG_PYTHON_2_UNICODE swigtest_wrap.cxx -lpython2.7 -o _swigtest.so
$ python2 useswig.py
baz
<type 'str'>

Is there any way to get that to output

<type 'unicode'>

instead? I understand from the docs that

When the SWIG_PYTHON_2_UNICODE macro is added to the generated code ... Unicode strings will be successfully accepted and converted from UTF-8, but note that they are returned as a normal Python 2 string

Is there a way to achieve that, possibly with a custom typemap somehow?

like image 731
Tavian Barnes Avatar asked Apr 21 '26 03:04

Tavian Barnes


1 Answers

A custom typemap works, but you'll need more to handle input parameters, output arguments, etc.

%module swigtest
%{
#include "swigtest.hpp"
%}

//%include <windows.i>  // Need for Windows DLLs to handle __declspec(dllexport)
//%include <std_string.i>
%typemap(out) std::string %{
    $result = PyUnicode_FromString($1.c_str());
%}

%include "swigtest.hpp"

%newobject new_foo;

Output:

C:\test>py -2 useswig.py
baz
<type 'unicode'>
like image 85
Mark Tolonen Avatar answered Apr 23 '26 16:04

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!