[C++-sig] Wrapping classical C API for python access

David Abrahams dave at boost-consulting.com
Tue Jun 28 16:20:12 CEST 2005


Markus Schöpflin <markus.schoepflin at comsoft.de> writes:

> David Abrahams wrote:
>
>> Markus Schöpflin <markus.schoepflin at comsoft.de> writes:
>
>> If you have a particular signature over and over again, you can do it
>> with a template:
>> 
>>   template <void (&f)(int, int*)>
>>   int thin_wrapper(int x)
>>   {
>>      int result;
>>      f(x,&result);
>>      return result;
>>   }
>> 
>> Then you can wrap
>> 
>>   thin_wrapper<foo>
>
> I see. Thanks for getting me started.
>
>>>And lastly, would "int bar(int a, int *b)" be convertible to "(ret,
>>>b) = bar(1)"?
>
>> Sorry, I don't understand.  A C++ type convertible to a Python
>> statement?
>
> Errm, no. What I meant is that the C++ function "int bar(int a, int *b)" 
> where the return value of bar and the output parameter b could be turned 
> into a tuple on the Python side, which would make the function callable 
> like "(ret, b) = bar(1)".

Sorry, I understand the concept, but not the question.  "I meant that
the C++ function ..., which would make the function callable..." just
doesn't parse.

> But as I'll have to write wrappers anyway, I'll have to do the conversion 
> manually I think. Is there by any chance some built-in support for using 
> boost.tuple together with boost.python, which would me enable to just write
>
> boost::tuple<int, int> bar_wrapper(int a)
> {
>    int b;
>    int ret = bar(a, &b);
>    return boost::make_tuple(ret, b);
> }

Why not just use boost::python::tuple?

template <int(&f)(int a, int*b)>
boost::python::tuple thin1(int x)
{
    int z;
    int r = f(x,&z);
    return make_tuple(r,z);
};

> and later on
>
> def("bar", bar_wrapper);

  def("bar", thin1<bar>)

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list