如何在 Julia 中定义指向变量或列表元素的指针?我尝试阅读一些资源,但我对在 Julia 中使用指针感到非常困惑。
最佳答案
你不能有一个指向变量的指针——与 C/C++ 不同,Julia 不是这样工作的:变量没有内存位置作为语言语义的一部分;编译器可能会将变量存储在内存中(或寄存器中),但这不关你的事😁。然而,可变对象通常存在于内存中,您可以使用pointer_from_objref
函数获取指向此类对象的指针:
pointer_from_objref(x)
Get the memory address of a Julia object as a
Ptr
. The existence of the resultingPtr
will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that thePtr
will be used.This function may not be called on immutable objects, since they do not have stable memory addresses.
See also:
unsafe_pointer_to_objref
.
为什么取这个可怕的名字?因为,你到底为什么要使用指向对象的指针?可能不要这样做。您还可以使用 pointer
函数获取指向数组的指针:
pointer(array [, index])
Get the native address of an array or string, optionally at a given location
index
.This function is "unsafe". Be careful to ensure that a Julia reference to
array
exists as long as this pointer will be used. TheGC.@preserve
macro should be used to protect thearray
argument from garbage collection within a given block of code.Calling
Ref(array[, index])
is generally preferable to this function as it guarantees validity.
这是一个更合理的用例,特别是对于与 C 或 Fortran 的互操作,但要小心。原始指针和垃圾收集之间的交互是棘手且危险的。如果您不进行互操作,那么请认真思考为什么需要指针 - 您可能希望以不同的方式解决问题。
关于pointers - 我可以在 julia 中定义指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125601/