Crystal C bindings: return type char*
Asked Answered
S

1

6

I have a function with this signature:

const char* get_version();

My declaration is:

fun get_version(): LibC::Char*

And to use it:

version = MyLib.get_version()
puts version # how to convert to String?

How can I manage the return string? Do I have to import also strlen to measure the length of the C string and covert it to Crystal string manually?

Sacksen answered 28/12, 2016 at 1:16 Comment(0)
C
6

You wrap the Char* pointer with String.new(MyLib.version). If you know the string length, you may call String.new(ptr, size) too.

Note that this will copy the data from the pointer, so the C binding may release its pointer without affecting the Crystal String.

Carthy answered 28/12, 2016 at 9:34 Comment(1)
Also, one probably wants to delete the pointer manually, only in case the source expects caller to do.Ihab

© 2022 - 2024 — McMap. All rights reserved.