How could I convert a string to Ptr{Cchar}

Viewed 47

I need as an argument to a C function i'm calling with ccall, a Ref{Cchar} (aka a char*) How I could I convert my string to a Ref{Cchar} ? Thanks a lot ! :)

1 Answers

If you are calling a function that takes char* you would typically use Cstring. From the documentation on calling C:

The Cstring type is essentially a synonym for Ptr{UInt8}, except the conversion to Cstring throws an error if the Julia string contains any embedded NUL characters (which would cause the string to be silently truncated if the C routine treats NUL as the terminator).

so to call the size_t strlen ( const char * str ) C function you can write:

julia> ccall("strlen", Csize_t, (Cstring,), "abc")
0x0000000000000003

or:

julia> ccall("strlen", Csize_t, (Ptr{UInt8},), "abc")
0x0000000000000003

If you are mutating the string you could do something like this:

julia> strvec = Vector{UInt8}(undef, 10)
10-element Vector{UInt8}:
[...]

julia> ccall("strcpy", Csize_t, (Ptr{UInt8},Cstring), strvec, "abcd")
0x00007f4ad6788a70

julia> strvec[1:4]
4-element Vector{UInt8}:
 0x61
 0x62
 0x63
 0x64

julia> String(strvec[1:4])
"abcd"

or even with a Julia string:

julia> str = "test"
"test"

julia> ccall("strcpy", Csize_t, (Ptr{UInt8},Cstring), str, "abcd")
0x00007f4ad6fed6f8

julia> str
"abcd"

to get a pointer from a String or Vector{UInt8} you can call pointer but you can also, as shown above, just let ccall handle the conversion.

Related