Cython:分配指针值,而不是指针本身

Cython: Assign pointer values, not the pointer itself

C/C++ 允许将一个指针的值赋给另一个相同类型的指针:

#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;
} 

上面*b = *a行可以用Cython写吗?

所有这些都失败了:

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.

使用 b[0] = a[0] 似乎可以解决问题。索引是取消引用指针的另一种方法。这是一些示例代码及其输出。

# 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)

如您所见,b的值已经改变,但指针仍然引用与以前相同的地址。

initial values 999 777
initial pointers 105553136305600 105553136304304
final pointers 105553136305600 105553136304304
final values 999 999