【问题标题】:How can I make SWIG return unicode objects for strings in Python 2?如何让 SWIG 返回 Python 2 中字符串的 unicode 对象?
【发布时间】:2017-06-28 03:12:35
【问题描述】:

我有类似以下的内容:

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 字符串返回

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

【问题讨论】:

  • 感谢MCVE。我不得不为 Windows 稍微调整一下,但仍然 +1。

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


【解决方案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'>

【讨论】:

  • 太棒了!如果我将相同的 .i 用于多种语言绑定,如何使该类型映射仅适用于 Python?
  • @TavianBarnes 当然,#ifdef SWIGPYTHON 在它周围。文档中列出了其他语言。
猜你喜欢
  • 1970-01-01
  • 2015-05-20
  • 2010-12-21
  • 2017-03-15
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
相关资源
最近更新 更多