我可以在 julia 中定义一个指针吗?

Can I define a pointer in julia?

如何在 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 resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr 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. The GC.@preserve macro should be used to protect the array 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 的互操作,但要小心。原始指针和垃圾收集之间的交互是棘手和危险的。如果您不进行互操作,那么请仔细考虑为什么需要指针——您可能想以不同的方式解决问题。