Initializing a Vector{Cuchar} (string) prior to calling a C function

Hi! I m declaring a 28 characters-long string variable before calling a C program as follows:

julia> datetime = Vector{Cuchar}(undef, 28)
28-element Vector{UInt8}:
 0x01
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
    ā‹®
 0x09
 0x01
 0x00
 0x00
 0x00
 0x70
 0xbd
 0xcf
 0x0e

Clearly, that memory location does contain non-null bytes in various places. When the C function returns the (correct) result, I get

julia> datetime
28-element Vector{UInt8}:
 0x32
 0x30
 0x30
 0x32
 0x2d
 0x30
 0x35
 0x2d
 0x30
 0x32
    ā‹®
 0x5a
 0x00
 0x00
 0x00
 0x00
 0x70
 0xbd
 0xcf
 0x0e

julia> dt = String(datetime)
"2002-05-02T02:00:00Z\0\0\0\0p\xbd\xcf\x0e"

Question: How can I initialize the memory location originally reserved for datetime in such a way (1) that each and every byte is a null byte, and (2) that the outcome would be "2002-05-02T02:00:00Z\0\0\0\0\0\0\0\0"?
Thanks for suggestions.

datetime = zeros(Cuchar, 28)

If the string is NUL-terminated and you want to convert it to a corresponding String, but not including the NUL character(s) (i.e. if you want "2002-05-02T02" in your case), you can do e.g.

dt = String(datetime[1:findfirst(iszero, datetime)-1])

or alternatively (using lower-level operations to avoid copying data unnecessarily).

dt = GC.@preserve datetime unsafe_string(pointer(datetime))
2 Likes

Thanks a lot, @stevengj: That is also an elegant way to initialize that variable.