如何让SWIG在Python 2中为字符串返回unicode对象?

时间:2017-02-09 22:27:45

标签: python c++ python-2.7 unicode swig

我有以下内容:

  

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'>

有没有办法让它输出

<type 'unicode'>

代替?我从docs了解

  

当SWIG_PYTHON_2_UNICODE宏添加到生成的代码中时... Unicode字符串将被成功接受并从UTF-8转换,但请注意它们将作为普通的Python 2字符串返回

有没有办法实现这一点,可能以某种方式使用自定义类型图?

1 个答案:

答案 0 :(得分:1)

自定义类型映射有效,但您需要更多来处理输入参数,输出参数等。

%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;

输出:

C:\test>py -2 useswig.py
baz
<type 'unicode'>