[C++-sig] call C-functions (by reference) from Python (using Boost.Python)

Lutz Lauterbach Lutz.Lauterbach at qimonda.com
Fri Dec 8 18:04:03 CET 2006

Roman Yakovenko <roman.yakovenko <at> gmail.com> writes:
> In general you will have to write small wrapper around every function
> that takes/returns Python immutable( C++ fundamentals, strings and enums) 
> by reference/pointer.

Thanks Roman, taking your advice (and another example from somewhere in this 
forum and your attached Boost-code example) I created little wrapper functions 
which make the thing work:

  void jz_void_float1(float a, float &b) { b=a; }
  void jz_void_float2(float a, float *b) { *b=a; }
  #include <boost/python.hpp>
  namespace bp = boost::python;
  bp::tuple py_jz_void_float1(float v1, float v2 ){
     return bp::make_tuple( v1,v2);
  bp::tuple py_jz_void_float2(float v1, float v2 ){
     return bp::make_tuple( v1,v2);

   using namespace bp;
      def("jz_void_float1", py_jz_void_float1);
      def("jz_void_float2", py_jz_void_float2);

> Also it is possible to automate the process of wrapper creation. Take
> a look on Py++ function transformation feature:
> C++ source code: http://tinyurl.com/yhsef5
> Py++ script( unit test), that exposes the declarations:
> http://tinyurl.com/yjs2uw
> I attached the generated code.

Unfortunately I cannot take your Py++ suggestion, cause I use Win2k and gcc 
(which GCCXML is not able to work with (neither cygwin nor mingw)) and my Py++ 
program would look more complicated than the whole Boost code, so I rather code 
the Boost stuff directly in C++ instead of exerting another tool ... even 
though the automation sounds very attractive.

But now I face another hurdle: I also want to return arrays from C. Using the 
above scheme:

  void jz_array(float a[], float b[]){
  #include <boost/python.hpp>
  namespace bp = boost::python;
  bp::tuple py_jz_array(){
     float v1[3];float v2[3];
     jz_array(v1, v2);
     return bp::make_tuple(v1,v2);
  using namespace bp;
  { def("jz_array",py_jz_array);}

does not work. It comiples, but when calling the function "jz_array" from 
Python it says

>>> jz_array()
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: No to_python (by-value) converter found for C++ type: float [3]

Do you know any solution?

More information about the Cplusplus-sig mailing list