[cctbxbb] Quick Boost python question

Nicholas Sauter nksauter at lbl.gov
Tue Feb 21 19:46:40 PST 2017


James,

I believe this example snippet performs the function you want.

*diff --git a/rstbx/diffraction/fastbragg/fastbragg_ext.cpp
b/rstbx/diffraction/fastbragg/fastbragg_ext.cpp*

*index d544d22..380e84f 100644*

*--- a/rstbx/diffraction/fastbragg/fastbragg_ext.cpp*

*+++ b/rstbx/diffraction/fastbragg/fastbragg_ext.cpp*

@@ -22,6 +22,13 @@ namespace boost_python { namespace {

   {

     return boost::python::make_tuple(1,2,3,4);

   }

+

+  static double

+  get_distance_mm(camera const& c) { return c.distance*1000.; }

+

+  static void

+  set_distance_mm(camera& c, double const& value) {

+      c.distance = value/1000.;}



   void

   init_module() {

@@ -57,6 +64,9 @@ namespace boost_python { namespace {

       .add_property("distance",

                      make_getter(&camera::distance,rbv()),

                      make_setter(&camera::distance,dcp()))

+      .add_property("distance_mm",

+                     make_function(&get_distance_mm,rbv()),

+                     make_function(&set_distance_mm,dcp()))

       .add_property("Ybeam",

                      make_getter(&camera::Ybeam,rbv()),

                      make_setter(&camera::Ybeam,dcp()))

Use it with this example python script:

from rstbx.diffraction.fastbragg import camera


c = camera()

c.distance = 10. # meters

print "distance is %f millimeters"%( c.distance_mm )


c.distance_mm = 10.

print "distance is %f meters"%( c.distance )


Output is:

distance is 10000.000000 millimeters

distance is 0.010000 meters

So problem solved.
Nick



Nicholas K. Sauter, Ph. D.
Senior Scientist, Molecular Biophysics & Integrated Bioimaging Division
Lawrence Berkeley National Laboratory
1 Cyclotron Rd., Bldg. 33R0345
Berkeley, CA 94720
(510) 486-5713

On Tue, Feb 21, 2017 at 5:08 PM, Nicholas Sauter <nksauter at lbl.gov> wrote:

> <http://phenix-online.org/mailman/listinfo/cctbxbb>Quick question from
> James Holton and myself.
>
> We want to use a boost python *.add_property() to add a make_getter and
> make_setter to our wrapper, so we can expose a class variable to the Python
> layer.
>
> However, we want to execute a change of measurement units, i.e., the
> Python value will always be given in millimetres, and the C++ value always
> in metres.
>
> How can this be done within a simple add_property() paradigm?
>
> Nick
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://phenix-online.org/pipermail/cctbxbb/attachments/20170221/1e0abd37/attachment.htm>


More information about the cctbxbb mailing list