2016-06-28 264 views
1

假設我有一個簡單的結構,單場:的Python:痛飲:將訪問封裝到一個struct

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 typemap的內容。 但我的例子不工作:

%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

回答

2

我已經自己解決了這個問題。重要的是,在界面中定義結構之前,需要定義類型映射。文件不清楚(或我沒有看到它)。此外,「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"