Is this the best way to convert a NUL terminated C-string into a Julia `String`?

Is this the best way to convert a NUL terminated C-string into a Julia String?

julia> typeof(text)
Array{UInt8,1}

julia> unsafe_string(pointer(text))
"C14120-20P"

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

1 Like

You have to be careful in general with this kind of code, because the pointer is not “rooted” — you need to make sure that text does not get garbage-collected into oblivion before unsafe_string is done with it. One option is to do:

GC.@preserve text s = unsafe_string(pointer(text))

Another option is to avoid “unsafe” pointer operations and do something like:

String(text[1:findfirst(==(0x00), text)-1])

What is the “best” way depends on what your criteria are, and in general will depend on the context. (For example, where does your text array come from? It might be possible to read directly into a string buffer without making a copy.)

1 Like