Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the right way to use pointer_from_objref() and Ref()?

Tags:

pointers

julia

just copying from the 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.

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.

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.

i want to pass a pointer to a c function. according to the doc, it seems like using pointer_from_objref is not always safe, so i try to use Ref instead:

# 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

the results show that test 2 gives an unexpected result without any error, but test 3 works fine when i convert bufferID into an array.

my question is why test 2 will give an unexpected result with no error occurred. for safety sake, is it right to always use Ref() instead of pointer_from_objref()? if yes, are there any side effects(e.g. performance)?

i'm using julia v"0.4.0-rc1".

like image 931
Gnimuc Avatar asked Nov 10 '22 03:11

Gnimuc


1 Answers

Check out this section: http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code/#passing-pointers-for-modifying-inputs

To follow that pattern, try the following, which works for me on other ccall() code. I think Ref{T} is an important part of memory allocation, and dereferencing by var[].

# test 4
bufferID = Ref{GLuint}(0)
glGenBuffers(1, bufferID)
@show bufferID[]
like image 54
Nicholas Utschig Avatar answered Nov 15 '22 05:11

Nicholas Utschig