pointers - 我可以在 julia 中定义指针吗?

标签 pointers julia language-design

如何在 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 的互操作,但要小心。原始指针和垃圾收集之间的交互是棘手且危险的。如果您不进行互操作,那么请认真思考为什么需要指针 - 您可能希望以不同的方式解决问题。

关于pointers - 我可以在 julia 中定义指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125601/

相关文章:

julia - 形成内积的最佳方法是什么?

function - 调用函数时声明参数名称

language-design - 为什么 COBOL 同时具有 `SECTION` 和 `PARAGRAPH` ?

rust - 为什么只能用特征指定类型限制?

database - 领域特定语言的有趣例子

c++ - 如何从指向结构的指针输出char数组中的整个字符串

C++,指向对象的指针重置字符串变量的值

c - 通过指针从动态分配的二维数组中获取值

c++ - 将指向类的指针 append 到 QList QList<Class* >

plot - 包装未定义