C/C++ allows assigning values of a pointer to another pointer of the same type:
#include <iostream>
using namespace std;
int main() {
int* a = new int();
int* b = new int();
*a = 999;
*b = *a; // Can't do in Cython this?
cout <<"Different pointers, same value:" <<endl;
cout <<a <<" " <<b <<endl;
cout <<*a <<" " <<*b <<endl;
}
Is it possible to write the line *b = *a
above in Cython?
All these fail:
from cython.operator cimport dereference as deref
cdef cppclass foo: # Can't `new int()` in Cython, make a class
int value
cdef foo* a = new foo()
cdef foo* b = new foo()
a.value = 999
deref(b) = deref(a) # Error: Cannot assign to or delete this
b = deref(a) # Error: Cannot assign type 'foo' to 'foo *'
deref(b) = a # Error: Cannot assign to or delete this
b = a # Works, but pointer 'b' is gone!!! not a clone.
Using b[0] = a[0]
seems to do the trick. Indexing is another way to dereference the pointer. Here's some example code and its output.
# distutils: language=c++
cdef cppclass foo:
int value
cdef foo* a = new foo()
cdef foo* b = new foo()
a.value = 999
b.value = 777
print('initial values', a.value, b.value)
print('initial pointers', <long>a, <long>b)
b[0] = a[0]
print('final pointers', <long>a, <long>b)
print('final values', a.value, b.value)
As you can see, the values of b
have changed, but the pointer still references the same address as before.
initial values 999 777
initial pointers 105553136305600 105553136304304
final pointers 105553136305600 105553136304304
final values 999 999