gpt4 book ai didi

julia - 我什么时候应该使用 Ptr 而不是 Ref

转载 作者:行者123 更新时间:2023-12-04 14:48:58 25 4
gpt4 key购买 nike

根据文档,Ptr{T}

A memory address referring to data of type T. However, there is no guarantee that the memory is actually valid, or
that it actually represents data of the specified type.

另一方面:

 Ref{T}

An object that safely references data of type T. This type is guaranteed to point to valid, Julia-allocated memory
of the correct type. The underlying data is protected from freeing by the garbage collector as long as the Ref
itself is referenced.

所以我的问题是:Ref 似乎与 Ptr 具有相同的用例,并且在任何情况下似乎都比 Ptr 更好。关于我们什么时候应该使用 Ptr{T} 而不是 Ref{T} 是否有一些规则?

最佳答案

当您将 C 混合到 Julia 中时它很有用(这并不奇怪,因为您引用的文档页面被命名为“C 接口(interface)”)。就像你说的,Ref 看起来像一个增强的 Ptr 保证有有效的 Julia 分配的内存由 Julia 的垃圾收集器处理。 Ptr 更适合包装在 C 端创建和处理的指针。准则写在一小节中 "When to use T, Ptr{T} and Ref{T}"在“调用 C 和 Fortran 代码”页面中:

In Julia code wrapping calls to external C routines, ordinary (non-pointer) data should be declared to be of type T inside the ccall, as they are passed by value. For C code accepting pointers, Ref{T} should generally be used for the types of input arguments, allowing the use of pointers to memory managed by either Julia or C through the implicit call to Base.cconvert. In contrast, pointers returned by the C function called should be declared to be of output type Ptr{T}, reflecting that the memory pointed to is managed by C only. Pointers contained in C structs should be represented as fields of type Ptr{T} within the corresponding Julia struct types designed to mimic the internal structure of corresponding C structs.

如果你正在做纯 Julia,你会想要坚持使用 Ref,尽管你不会经常需要它,因为引用通常出现在具有抽象类型的可变对象或结构字段中. Ref 在广播中使可迭代成为标量并将不可变对象(immutable对象)包装在可变引用中非常有用。

关于julia - 我什么时候应该使用 Ptr 而不是 Ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69373435/

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