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

Roman Yakovenko roman.yakovenko at gmail.com
Wed Dec 6 11:25:54 CET 2006


On 12/6/06, Lutz.Lauterbach at qimonda.com <Lutz.Lauterbach at qimonda.com> wrote:
> I have been successfully installing and using Boost.Python on Win2k for
> a
> short while, providing C-functions to Python which uses call-by-value
> and even a variable number of parameters. But since some days I get
> stuck at the problem of passing parameters from Python to C using
> call-by-reference. Here two little (simplified!) examples:
>
>   void jz_void_float1(float a, float &b) { b=a; }
>   void jz_void_float2(float a, float *b) { *b=a; }
>
>   #include <boost/python.hpp>
>   using namespace boost::python;
>   BOOST_PYTHON_MODULE(hello) {
>      def("jz_void_float1", jz_void_float1);
>      def("jz_void_float2", jz_void_float2);
>   }
>
> It compiles without errors and I can call the function in Python, but
> then it complains about the types:
>
>   >>> var=3.3
>   >>> jz_void_float1(4.4,var)
>      Traceback (most recent call last): File "<stdin>", line 1, in ?
>      Boost.Python.ArgumentError: Python argument types in
>      hello.jz_void_float(float, float) did not match C++ signature:
>      jz_void_float(f, f {lvalue})
>
> I would like to know how to "convert" the types or whether this idea of
> implementation is doable at all (or whether another thin-wrapper "layer"
> is
> necessary or whatever). I have seen the pointer-stuff working with char
> types, but all the others were failing.
>
> The intention of the call-by-reference is obviously to change the
> Python-value directly via the pointer, since there is only one return
> value, but we want to modify/return several data from the C-function.
>
> Please do not say "Boost.Python was designed for C++ and not for C, so
> better use SWIG or whatever",

I will not say this :-) Boost.Python is still perfectly good for the task.
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.

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.

The documentation to the feature is under development right now,
nevertheless it should
be pretty useful.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: function_transformations.cpp
Type: text/x-c++src
Size: 18334 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20061206/81c99c6e/attachment.cpp>


More information about the Cplusplus-sig mailing list