[C++-sig] C++ and Python variables referencing the same location

David Abrahams dave at boost-consulting.com
Fri Aug 11 00:54:23 CEST 2006


tcickovs at nd.edu writes:

> Hello,
> I have been working on something for the past few days and have not been able to
> find much online help on it.  Conceptually, what I want to do is very simple: I
> would like to declare a C++ variable, then use the Python/C API (or some other
> available utility) to define a Python variable, and then somehow get the two to
> reference the same memory location so that when I modify one, the other changes.
> So, for example, in my C++ file if I have this:
>
> object main_module((
>                            handle<>(borrowed(PyImport_AddModule("__main__")))));
> int y = 2;  // y = 2
> main_module.attr("x") = y;  // x = 2, y = 2
> main_module.attr("x") = 3;  // x = 3, y = 2 (does not change)
> y = 4;    // x = 3 (does not change), y = 4

You can't do it with assignment syntax, since in Python that always
rebinds.

> Modifications to x and y happen independently because one is on the C++ runtime
> stack and the other is on the Python interpreter's heap.  I'd like it to be if
> I modify x, then y changes; and vice-versa.
>
> Now, I saw in the Python/C API there was a way to modify information in the
> Python interpreter heap from C++:
>
> int* y = PyMem_New(int, 1);
> *y = 4;  // Changes data in the heap
>
> However, I need to somehow get x to reference the location in the heap that I
> just allocated.  Is there a way?

No; for another reason, Python ints are immutable.  Changing the
stored value would break _everything_.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list