[C++-sig] pass float from python to c++ as reference
Matthew Scouten
matthew.scouten at gmail.com
Tue Feb 19 16:41:58 CET 2008
You can do something like this, if you do not mind cluttering up the
interface on the python side:
struct DoubleByReference
{
public:
inline DoubleByReference(){;}
inline DoubleByReference(double num):value_(num) {;}
inline DoubleByReference(const DoubleByReference & rhs) {value_ =
rhs.value_;}
inline double* address() {return &value_;}
inline double& ref() {return value_;}
double get_value() {return value_;}
void set_value(double value) {value_ = value;}
private:
double value_;
};
class_<DoubleByReference >("DoubleByReference")
.def(init<>())
.def(init<double>())
.add_property("value", &IntByReference::get_value,
&IntByReference::set_value)
;
void by_reference_wrapper(DoubleByReference &x){
by_reference(x.ref());
Like I said, it's not pretty, but it works.
On Feb 19, 2008 4:48 AM, Sebastian Walter <walter at mathematik.hu-berlin.de>
wrote:
> Hello,
> I need to pass a float from Python to C++ as a reference. What is the best
> way to do that? I can't find it in the unit tests:
> boost_1_34_1/libs/python/test/test_builtin_converters.cpp
>
>
> /* by_reference.cpp */
> #include <boost/python.hpp>
>
> void by_reference(double &x){
> x = 23.;
> }
> BOOST_PYTHON_MODULE(mymodule)
> {
> using namespace boost::python;
> def("by_reference", by_reference);
> }
>
>
>
> /* by_reference.py */
> import mymodule
>
> x = 1.
> print x
> mymodule.by_reference(x)
> print x
>
> /* output */
> >>Traceback (most recent call last):
> >> File "./test.py", line 7, in <module>
> >> mymodule.by_reference(x)
> >>Boost.Python.ArgumentError: Python argument types in
> >> mymodule.by_reference(float)
> >>did not match C++ signature:
> >> by_reference(double {lvalue})
>
>
>
> thanks in advance,
> Sebastian Walter
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20080219/57bd5d4f/attachment.htm>
More information about the Cplusplus-sig
mailing list