swig 를 사용해서 파이썬 바인딩을 만들다보면
std::string 이나 std::wstring 을 뽑아내야 할 경우가 있습니다.

[code c++]
std::string GetFilePath()
{
return m_filePath;
}


공식적인 사용방법은 단지 std_string.i 를 include 해주면 됩니다.


%module 모듈네임

%include "std_string.i"

%{
%include "변환할헤더.h"
%}

%include "변환할헤더.h"


그런데...

리턴된 std::wstring 을 print 해보려고 하거나
[code c++]
std::wstring GetFilePathW()
{
return m_filePath;
}


print GetFilePathW() # 에러 발생


std::wstring 에 유니코드 값을 직접 넣으려고 하면
[code c++]
struct Data
{
std::wstring name;
};


data = Data()
data.name = u"haha" # 에러 발생

문제가 발생합니다.

이런 경우에는 다음처럼 typemap 을 구현해주면 잘 해결이 됩니다

%typemap(in) std::wstring {
if (PyUnicode_Check($input))
{
$1 = std::wstring((wchar_t*)PyUnicode_AS_DATA($input), PyUnicode_GetSize($input));
}
else
{
PyErr_SetString(PyExc_TypeError, "NOT_UNICODE");
return NULL;
}
}

%typemap(out) std::wstring {
$result = PyUnicode_FromWideChar($1.c_str(), $1.size());
}

슥슥 ~(-_-)~
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/02/11 18:56 2009/02/11 18:56