gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:12:28 30 4
gpt4 key购买 nike

如何在 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 ofthe resulting Ptr will not protect the object from garbage collection,so you must ensure that the object remains referenced for the wholetime that the Ptr will be used.

This function may not be called on immutable objects, since they donot 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 givenlocation index.

This function is "unsafe". Be careful to ensure that a Julia referenceto array exists as long as this pointer will be used. The GC.@preservemacro should be used to protect the array argument from garbagecollection within a given block of code.

Calling Ref(array[, index]) is generally preferable to this functionas it guarantees validity.

这是一个更合理的用例,特别是对于与 C 或 Fortran 的互操作,但要小心。原始指针和垃圾收集之间的交互是棘手且危险的。如果您不进行互操作,那么请认真思考为什么需要指针 - 您可能希望以不同的方式解决问题。

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com