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 !
:)
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 !
:)
If you are calling a function that takes char* you would typically use Cstring. From the documentation on calling C:
The
Cstringtype is essentially a synonym forPtr{UInt8}, except the conversion toCstringthrows 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.