2

I am currently writing a ccall binding for the ChakraCore JavaScript engine and there is one function with this definition:

CHAKRA_API JsStringToPointer(
    _In_ JsValueRef stringValue,
    _Outptr_result_buffer_(*stringLength) const WCHAR **stringPtr,
    _Out_ size_t *stringLength
)

So I create a Ref to a WCHAR via: resultWC = Ref{Cwstring}()

I tried a bunch of convert functions to get a String back, but nothing worked yet. I guess I need this: https://docs.julialang.org/en/v0.6.1/stdlib/strings/#Base.transcode

But Base.transcode wants a Vector/Array and I don't know how to do simple C-style casting in Julia for this case.

Any ideas how to turn a Ref{Cwstring}() into a String?

rickhg12hs
  • 3,555
  • 14
  • 36
kungfooman
  • 3,696
  • 1
  • 32
  • 25

1 Answers1

2

You're right, it's a problem.

Until that is fixed, you can add your own method:

function Base.unsafe_string(w::Cwstring)
    ptr = convert(Ptr{Cwchar_t}, w)
    ptr == C_NULL && throw(ArgumentError("cannot convert NULL to string"))
    buf = Cwchar_t[]
    i = 1
    while true
        c = unsafe_load(ptr, i)
        if c == 0
            break
        end
        push!(buf, c)
        i += 1
    end
    return String(transcode(UInt8, buf))
end

Then you can just call it by

unsafe_string(resultWC[])
Simon Byrne
  • 7,284
  • 1
  • 21
  • 43
  • Thanks, works also with Emojis, even tho Windows cmd.exe can't display most of them correctly in 2018. :D – kungfooman Aug 24 '18 at 07:24
  • At some point we hope to bundle our own terminal (https://github.com/JuliaLang/julia/issues/7267), until then you could try something like http://cmder.net/ – Simon Byrne Aug 24 '18 at 15:42