基本型別對映 - Python

給定以下自定義布林型別我們要包裝:

typedef char MYBOOL;
#define TRUE 1
#define FALSE 0

一種簡單的方法可能是在 SWIG 介面中編寫以下型別圖:

%typemap(in) MYBOOL %{
  // $input is what we got passed from Python for this function argument
  $1 = PyObject_IsTrue($input);
  // $1 is what will be used for the C or C++ call and we are responsible for setting it
%}

%typemap(out) MYBOOL %{
  // $1 is what we got from our C or C++ call
  $result = PyBool_FromLong($1);
  // $result is what gets given back to Python and we are responsible for setting it
%}

使用這些型別對映,每次看到 MYBOOL 傳入或傳出函式呼叫時,SWIG 都會將程式碼插入到生成的包裝器中。