【问题标题】:what's the right way to use pointer_from_objref() and Ref()?使用 pointer_from_objref() 和 Ref() 的正确方法是什么?
【发布时间】:2015-10-07 12:40:10
【问题描述】:

只是从doc复制过来的:

pointer_from_objref(object_instance):

生成的 Ptr 的存在不会保护对象免受垃圾回收,因此您必须确保该对象在 Ptr 将被使用的整个时间内保持引用。

参考{T}:

一个安全引用类型 T 数据的对象。该类型保证指向正确类型的有效 Julia 分配内存。只要引用了 Ref 本身,底层数据就不会被垃圾收集器释放。

当作为 ccall 参数(作为 Ptr 或 Ref 类型)传递时,Ref 对象将被转换为指向它所引用数据的本机指针。

没有无效 (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 给出了意外的结果而没有任何错误,但是当我将bufferID 转换为数组时test 3 工作正常。

我的问题是为什么test 2 会给出一个未发生错误的意外结果。为了安全起见,总是使用Ref() 而不是pointer_from_objref() 是否正确?如果是,是否有任何副作用(例如性能)?

我正在使用julia v"0.4.0-rc1"

【问题讨论】:

    标签: pointers julia


    【解决方案1】:

    查看此部分: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[]
    

    【讨论】:

    • 谢谢! test2 是错误的模式。从更新的section来看,推荐Ref
    猜你喜欢
    • 2016-12-16
    • 1970-01-01
    • 2019-05-17
    • 2014-12-08
    • 1970-01-01
    • 2023-03-15
    • 2011-11-11
    • 2015-03-01
    • 1970-01-01
    相关资源
    最近更新 更多