Garbage collector for string arrays

I have generated several strings in the C api via jl_cstr_to_string(x) and pushed them to the gc stack.
Then I create an array of strings by passing an array of the respective string pointers.
Now the critical question:
Can I release the single string variables from the gc stack after having created the array?
One could hope that the GC now cares about the array and the array contains the references to the strings.

ReDim s(1 To 3) As String
s(1) = "Hello"
s(2) = "World"
s(3) = "!"

JL_GC_PUSH VarPtr(jl_a)      '# rooting of the Julian string array
JL_GC_PUSHARGS jl_p, 3       '# rooting of the array of Julian string pointers

For i = 1 To 3            ' # create Julian strings from C pointers
    jl_p(i - 1) = jl_cstr_to_string(s(i))

jl_a_type = jl_apply_array_type(jl_string_type, 1)
jl_a = jl_ptr_to_array_1d(jl_a_type, VarPtr(jl_ss(0)), 2, 0)   '# own_buffer = 0 as I am still in charge of jl_a

JL_GC_POP                           '# unroot the jl_p array ... ????

'# do something with a, e.g. trigger the garbage collector
'# by requiring huge memory
jl_eval_string "collect(1:10_000_000)"
MsgBox jl_typeof_str(jl_a)       '# returns a pointer, so the variable is still alive in Julia
MsgBox jl_typeof_str(jl_p(0))    '# returns a pointer, so the variable is still alive in Julia
JL_GC_POP                           '# unroot jl_a

jl_eval_string "collect(1:10_000_000)"
MsgBox jl_typeof_str(jl_a)    '# returns 0, so the variable was deleted
MsgBox jl_typeof_str(jl_p(0))    '# returns 0, so the variable was deleted

I found the solution myself by testing, but I think, others might still enjoy the example …
So my conclusion is, the single variables can be unrooted. But in order to work, jl_a has to be rooted first, as the GC is a LiFo buffer.
P.S.: Sorry for using VB syntax, but hey, Julia also works in Excel :wink:

1 Like