基本类型映射 - 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 都会将代码插入到生成的包装器中。