2011-02-14 142 views
2

我是Python C綁定swig的新手,一直在試圖解決這個問題。我有一個我想從Python調用的外部C庫(Example.c)。我閱讀Swig教程並能夠立即生成包裝器。現在的問題是,當我調用API,我得到了這一點:swig,python和wchar_t問題

>>> import Example 
>>> dir(Example) 
['Example_CreateConnection', 'trimmed to fit the screen'] 
>>> Example.Example_CreateConnection("") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: in method 'Example_CreateConnection', argument 1 of type 'ExampleChar const *' 

這似乎是無法找到的類型ExampleChar。以下是我痛飲文件:

%module Example 
%{ 
#include "ExampleSDK.h" 
%} 

%include "ExampleTypes.h" 
%include "ExampleSDK.h" 

ExampleTypes.h看起來是這樣的:

#ifndef ExampleTypes_H 
#define ExampleTypes_H 

typedef wchar_t ExampleChar; 

#endif /* ExampleTypes_H */ 

ExampleSDK.h看起來是這樣的:

#ifndef ExampleSDK_H 
#define ExampleSDK_H 

#include "ExampleTypes.h" 
void Example_CreateConnection(const ExampleChar *temp); 

#endif /* ExampleSDK_H */ 

下面是被調用的命令行生成包裝:

swig -python -I. Example.i 
gcc -c Example.c -I/Developer/SDKs/MacOSX10.6.sdk/usr/include/ 
gcc -c Example_wrap.c -I/usr/include/python2.6 -I. 
gcc -bundle -flat_namespace -undefined suppress -o _Example.so Example_wrap.o Example.o -L/usr/lib/python2.6/config/ -lpython2.6 

這裏是Example.c的樣子:

#include "runetype.h" // for Mac wchar_t definition 

#include "ExampleSDK.h" 

void Example_CreateConnection(const ExampleChar *temp) 
{ 
    //do nothing 
} 

我不知道什麼是錯的。我希望有人能夠指出我在這裏完成的錯誤。謝謝。

問候,

傳林

回答

2

我最後一次痛飲+ Python中wchat_t我最終需要添加類似:

%include "pywstrings.swg" 
%include "pystrings.swg" 
%include "std_string.i" 
%include "typemaps.i" 

%fragment("SWIG_AsVal_wchar_t", "header", fragment="<wchar.h>") { 
    SWIGINTERN int SWIG_AsVal_wchar_t(PyObject* p, wchar_t* c) { 
     return SWIG_OK; 
    } 
} 
%fragment("SWIG_From_wchar_t", "header", fragment="<wchar.h>") { 
    SWIGINTERNINLINE PyObject* SWIG_From_wchar_t(wchar_t c) { 
     return SWIG_Py_Void(); 
    } 
} 

// Python -> C 
%typemap(in) wchar_t const * { 
    $1 = PyString_to_wchar_t($input); 
} 

// C -> Python 
%typemap(out) wchar_t * { 
    $result = wchar_t_to_PyObject($1); 
} 
在我痛飲接口文件

+0

感謝您的信息。由於前一段時間的截止日期,我已經轉到CType。我相信它的工作原理,我感謝您的幫助:) – chuan 2011-05-04 09:05:13