3

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?

1
  • 1
    Thank you for an good MCVE. I had to tweak it slightly for Windows, but still +1. Commented Feb 10, 2017 at 2:57

1 Answer 1

2

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'>
Sign up to request clarification or add additional context in comments.

2 Comments

Great! If I'm using the same .i for multiple language bindings, how can I make that typemap only apply to Python?
@TavianBarnes Sure, #ifdef SWIGPYTHON around it. Other languages are listed in the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.