gpt4 book ai didi

pointers - 使用pointer_from_objref() 和Ref() 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-04 21:38:15 26 4
gpt4 key购买 nike

只是从 doc 复制:
pointer_from_objref(object_instance):

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.


引用{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.

When passed as a ccall argument (either as a Ptr or Ref type), a Ref object will be converted to a native pointer to the data it references.

There is no invalid (NULL) Ref.


我想传递一个指向 c 函数的指针。根据文档,似乎使用 pointer_from_objref并不总是安全的,所以我尝试使用 Ref反而:
# test 1
bufferID = convert(GLuint, 0)
glGenBuffers(1, pointer_from_objref(bufferID))
@show bufferID

out => bufferID = 0x00000001 # ok

# test 2
bufferID = convert(GLuint, 0)
glGenBuffers(1, Ref(bufferID))
@show bufferID

out => bufferID = 0x00000000 # unexpected result

# test 3
bufferID = GLuint[0]
glGenBuffers(1, Ref(bufferID))
@show bufferID[]

out => bufferID[] = 0x00000001 # ok
结果显示 test 2给出了一个没有任何错误的意外结果,但是 test 3当我转换时工作正常 bufferID成一个数组。
我的问题是为什么 test 2将给出未发生错误的意外结果。为了安全起见,始终使用 Ref() 是否正确?而不是 pointer_from_objref() ?如果是,是否有任何副作用(例如性能)?
我正在使用 julia v"0.4.0-rc1" .

最佳答案

查看此部分:http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code/#passing-pointers-for-modifying-inputs

要遵循该模式,请尝试以下操作,它适用于其他 ccall() 代码。我认为 Ref{T} 是内存分配的重要组成部分,并通过 var[] 取消引用。

# test 4
bufferID = Ref{GLuint}(0)
glGenBuffers(1, bufferID)
@show bufferID[]

关于pointers - 使用pointer_from_objref() 和Ref() 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992475/

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