What is the correct way to use pointer_from_objref () and Ref ()?

just copying from 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 a reference for the entire time you use Ptr.

Link {T}:

An object that safely references data of type T. This type is guaranteed to point to the valid memory allocated by Julia of the correct type. The source data is protected from being freed by the garbage collector if it refers to the Ref.

When passing ccall as an argument (as in the form of Ptr or Ref), the Ref object will be converted into its own pointer to the data associated with it.

There is no invalid (NULL) link.

I want to pass a pointer to a function c. according to the document, it seems that using pointer_from_objref not always safe, so I'm trying 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 great when converting bufferID to an array.

my question is why test 2 will give an unexpected result without causing an error. for security's sake, is it always correct to use Ref() instead of pointer_from_objref() ? if so, are there any side effects (e.g. performance)?

I am using julia v"0.4.0-rc1" .

+5
source share
1 answer

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

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

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

Source: https://habr.com/ru/post/1233159/


All Articles