我可以在 julia 中定义一个指针吗? [英] Can I define a pointer in julia?

查看:118
本文介绍了我可以在 julia 中定义一个指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Julia 中定义指向变量或列表元素的指针?我曾尝试阅读一些资源,但我对在 Julia 中使用指针感到非常困惑.

How do I define a pointer to a variable or list element in Julia? I have tried reading some resources but I am really confused about using a pointer in Julia.

推荐答案

你不能有一个指向变量的指针——与 C/C++ 不同,Julia 不是这样工作的:变量没有内存位置.您可以使用 pointer_from_objref 函数获得指向堆分配对象的指针.

You cannot have a pointer to a variable—unlike C/C++, Julia doesn't work like that: variables don't have memory locations. You can have a pointer to heap-allocated objects using the pointer_from_objref function.

pointer_from_objref(x)

获取 Julia 对象的内存地址作为 Ptr.的存在结果 Ptr 不会保护对象免受垃圾收集,所以你必须确保整个对象保持引用Ptr 将被使用的时间.

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.

另见:unsafe_pointer_to_objref.

为什么这个可怕的名字?因为,真的为什么要使用指向对象的指针?可能不要那样做.您还可以使用 pointer 函数获取指向数组的指针:

Why the awful name? Because, really why are you taking pointers to objects? Probably don't do that. You can also get a pointer into an array using the pointer function:

pointer(array [, index])

获取数组或字符串的本机地址,可选地在给定的位置 index.

Get the native address of an array or string, optionally at a given location index.

这个函数是不安全的".小心确保 Julia 引用只要将使用此指针,to array 就存在.GC.@preserve宏应该用于保护 array 参数免受垃圾影响给定代码块内的集合.

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.

调用 Ref(array[, index]) 通常比这个函数更可取因为它保证了有效性.

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

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

This is a somewhat more legitimate use case, especially for interop with C or Fortran, but be careful. The interaction between raw pointers and garbage collection is tricky and dangerous. If you're not doing interop then think hard about why you need pointers—you probably want to approach the problem differently.

这篇关于我可以在 julia 中定义一个指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆