【问题标题】:Python: SWIG: Wrap Access to a StructPython:SWIG:包装对结构的访问
【发布时间】:2016-06-28 15:56:01
【问题描述】:

假设我有一个带有单个字段的简单结构:

typedef struct {
    MY_UNICODE value[512];
} TEST_STRUCTURE

MY_UNICODE 是一个自定义的 unicode 实现。 另外我有两种方法:

int UTF8ToMyUnicode(char *utf8, MY_UNICODE *unicode);
int MyUnicodeToUTF8(MY_UNICODE *unicode, char *utf8);

从和转换到这个自定义类型。 现在我可以使用SWIG为此生成一个Python接口。 但是当我尝试在 Python 中访问 TESTSTRUCTURE.value 时。我总是得到一个指向 MY_UNICODE 对象的点。

我的问题是:如何包装对结构成员的访问,以便获得 python 字符串并可以使用 python 字符串设置值?

我知道 SWIG 的文档中提到了 memberin 类型映射。 但我的例子不起作用:

%module test
%include "typemaps.i"
// This is the header file, where the structure and the functions are defined
%include "test.h"

%typemap(memberin) MY_UNICODE [512] {
    if(UTF8ToMyUnicode($1, $input) != 0) {
        return NULL;
    }
}

%typemap(memberout) MY_UNICODE [512] {
    if(MyUnicodeToUTF8($1, $input) != 0) {
        return NULL;
    }
}    

在生成的包装文件中,还没有应用地图。

任何帮助将不胜感激!谢谢!

PS:我使用的是 swig 2.0.10

【问题讨论】:

    标签: python c swig


    【解决方案1】:

    我自己解决了这个问题。重要的是需要在接口中定义结构之前定义类型映射。文档对此并不清楚(或者我没有看到)。此外,“in”和“out”类型映射可用于转换值。 这个例子对我有用:

    %module test
    %include "typemaps.i"
    
    %typemap(in) MY_UNICODE [512] {
        if(UTF8ToMyUnicode($1, $input) != 0) {
            return NULL;
        }
    }
    
    %typemap(out) MY_UNICODE [512] {
        if(MyUnicodeToUTF8($1, $result) != 0) {
            return NULL;
        }
    }
    // Now include the header file
    %include "test.h"
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 2012-04-23
      • 2010-11-02
      • 2017-12-07
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多