[C++-sig] Pyste,Py++: equivalent of swig typemaps?

Roman Yakovenko roman.yakovenko at gmail.com
Sun Nov 30 22:13:50 CET 2008


On Sun, Nov 30, 2008 at 10:56 PM, Stefan Seefeld <seefeld at sympatico.ca> wrote:
> Mihail Konstantinov wrote:
>>
>> Thank you Stefan,
>> the typemaps are required, when C++ functions are wrapped that expect
>> arguments which have no direct corresponding type in python, or when
>> standard types have to be interpreted differently.
>>
>> For example a function void parse_args(int argc, char **argv), which I
>> want to call in python as mymodule.parse_args(["arg1","arg2","arg3"]). The
>> wrapper would have to - count the number of python list items and pass this
>> as argc to the C++ function
>> - allocate and fill a list of char* with the strings from the python list.
>>
>
> What about this ?
>
> void parse_args(list argv)
> {
>  std::vector<std::string> args;
>  for (unsigned int i = 0; i != len(argv); ++i)
>  {
>   extract<char const *> ex(argv[i]);
>   if (ex.check()) // If this is really a string...
>     args.push_back(ex); // ...copy it into a vector
>   else
>     throw some_error();
>  }
>  my_function(args);
> }
>
>
> This does what you seem to want: translates a python list of strings into a
> std::vector<std::string>, and passes it down to a function.
> Obviously, you can (attempt to) extract data of arbitrary types from the
> python list, as long as converters exist.

There are few problems with this approach:

* It doesn't scale well. Consider exporting the existing project,
which has 50-100 functions, which require different transformation.

* Although you have to write different code if you want to export
[none virtual | virtual | pure virtual] [free | member] function.

If I understand right SWIG feature, it allows you to define something
like "call policy" which is invoked before and after function
invocation, and it also allows you to define complex mapping between
Python and C++ arguments. So you can define it once, and then apply it
when needed.
I could be wrong, but you cant define such "call policy" using
Boost.Python. Code generators definitely help in this situation.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/


More information about the Cplusplus-sig mailing list