Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

julia - 我可以在julia中定义一个指针吗?(Can I define a pointer in julia?)

How do I define a pointer to a variable or list element in Julia?

(如何在Julia中定义指向变量或列表元素的指针?)

I have tried reading some resources but I am really confused about using a pointer in Julia.

(我曾尝试阅读一些资源,但对于在Julia中使用指针感到非常困惑。)

  ask by bitWise translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot have a pointer to a variable—unlike C/C++, Julia doesn't work like that: variables don't have memory locations.

(您不能拥有指向变量的指针-与C / C ++不同,Julia不能那样工作:变量没有内存位置。)

You can have a pointer to heap-allocated objects using the pointer_from_objref function.

(您可以使用pointer_from_objref函数获得一个指向堆分配对象的指针。)

pointer_from_objref(x)

Get the memory address of a Julia object as a Ptr .

(获取一个Julia对象的内存地址作为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.

(结果Ptr的存在不会保护对象免受垃圾回收的影响,因此您必须确保在使用Ptr的整个过程中始终保持对对象的引用。)

This function may not be called on immutable objects, since they do not have stable memory addresses.

(不能在不可变对象上调用此函数,因为它们没有稳定的内存地址。)

See also: unsafe_pointer_to_objref .

(另请参阅: unsafe_pointer_to_objref 。)

Why the awful name?

(为什么叫这个可怕的名字?)

Because, really why are you taking pointers to objects?

(因为,真的为什么要使用指向对象的指针?)

Don't do that.

(不要那样做)

You can also get a pointer into an array using the pointer function:

(您还可以使用pointer函数将指针放入数组:)

pointer(array [, index])

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

(获取数组或字符串的本机地址,可以选择在给定的位置index 。)

This function is "unsafe".

(此功能是“不安全的”。)

Be careful to ensure that a Julia reference to array exists as long as this pointer will be used.

(请注意,只要使用此指针,就必须确保存在Julia对array引用。)

The GC.@preserve macro should be used to protect the array argument from garbage collection within a given block of code.

(应该使用GC.@preserve宏来保护array参数免受给定代码块中的垃圾回收。)

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

(通常Ref(array[, index])调用Ref(array[, index])比此函数更可取,因为它可以确保有效性。)

Why do you want to use pointers in Julia code?

(为什么要在Julia代码中使用指针?)

If it's to interoperate with C, ok, that's a valid reason.

(如果要与C互操作,那是一个正当的理由。)

Be careful.

(小心。)

If it's for something else, you should probably approaching the problem differently.

(如果是其他原因,您可能应该以不同的方式处理问题。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...