typemaps_development

Joris Gillis edited this page Jun 11, 2011 · 2 revisions

Meta structure

We heavily rely on templates and SWIG macros to reduce the burden of maintaining typemaps. This section explains the meta class, which has only static members.

Basics

GUESTOBJECT: object arriving from the interfaced language CPPOBJECT: clean CPP object or primitive that you would use when developing C++ code SWIGOBJECT: An object that is a thin wrapper around CPPOBJECT, introduced by SWIG

The basic meta class members are: meta<T>:couldbe: returns a boolean that indicates if the GUESTOBJECT could ultimately be converted into CPPOBJECT of type T meta<T>:as: Converts the GUESTOBJECT to a CPPOBJECT. Returns false on failure. meta<T>:expected_message: The error message that will be thrown when a typemap receives a failed meta<T>:as call

Typical code

Suppose we have a type Type.

We would typically have a place where we define the SWIG name:

%inline %{
template<> swig_type_info** meta< Type >::name = &SWIGTYPE_Type;
%}

The python implementation looks like:

/// Type
#ifdef SWIGPYTHON
%inline %{
template<> char meta< Type >::expected_message[] = "Expecting Type";

template <>
int meta< Type >::as(PyObject * p, Type &m) {
NATIVERETURN(Type,m)
  // Some other magic
return false;
}

template <>
bool meta< Type >::couldbe(PyObject * p) {
return p.isType();
}
%}
%enddef
#endif //SWIGPYTHON

The octave implementation looks like:

/// Type
#ifdef SWIGOCTAVE
%inline %{
template<> char meta< Type >::expected_message[] = "Expecting Type";

template <>
int meta< Type >::as(const octave_value& p, Type &m) {
  // Some other magic
return false;
}

template <>
bool meta< Type >::couldbe(const octave_value& p) {
return p.isType();
}
%}
%enddef
#endif //SWIGOCTAVE

Advanced

meta<T>:name: The SWIG type name for T meta<T>:isa: returns a boolean that indicates if the GUESTOBJECT is a SWIGOBJECT in disguise meta<T>:expected_message: The error message that will be thrown when a typemap receives a failed meta<T>:as call meta<T>:couldbe_sequence: (Python only, default implementation) Checks if the GUESTOBJECT could be a sequence of CPPOBJECTS of type T meta<T>:as_vector: (Python only, default implementation) Attempts to make a std::vector of CPPOBJECTS of type T from the GUESTOBJECT

Macro's

NATIVERETURN: (Python only) Speedy return inside meta<T>::as when a GUESTOBJECT is a SWIGOBJECT in disguise %my_generic_const_typemap: Writes a simple input typemap for 'const std::vector<T>&', using meta<T> %meta_vector: Writes a meta< std::vector<T> > explicitation using meta<T>::couldbe_sequence and meta<T>::as_vector. %meta_pair: