[C++-sig] wrap global variable (def not work)

Nicodemus nicodemus at globalite.com.br
Wed Jun 4 17:54:01 CEST 2003


Zhang Le wrote:

>Hello, 
>  I want to wrap a single int variable to python model but failed:
>  the code is:
>  int verbose = 1;
>  BOOST_PYTHON_MODULE(foo)
>  {
>      def("verbose", &verbose);
>  }
>
>  <snip error message>
>
>    It seems def can only be used on class members. Any tips?
>

Try this:

int verbose = 1;
int get_verbose() { return verbose; }
BOOST_PYTHON_MODULE(foo)
{
    scope().attr("verbose") = verbose;
    def("get_verbose", &get_verbose);
}

But there's one problem:

>>> import foo
>>> foo.verbose
1
>>> foo.verbose = 2
>>> foo.verbose
2
>>> foo.get_verbose()
1

Ie, changes in a global variable won't be seen in C++, so this technique works only for constants. If you *really* need to be able to change the global variable from Python, you will have to create accessor functions and use these. That's not Boost.Python fault really, is just that in Python there's no way to know when a module-variable is *rebound* (note, not *changed*).

HTH,
Nicodemus.







More information about the Cplusplus-sig mailing list