Is StringLiteral intended for handling c strings?
Suppose I have c-library function in
thing.c
that returns a string. What datatype should I use to represent the return type for a FFI binding in a Mojo program?
Compile to shared library: clang -shared -o libThing.so thing.c
Option 1: UInt8 pointer
If I specify that the return type is a char/uint8 pointer, then I need to write a function parseCharArrayToString
that builds a string by loading each character until a null terminator is reached. This approach works fine.
Option 2: StringLiteral (Broken?)
I could instead specify the return type to be a StringLiteral
.
The value printed by the above program is correct. However, the length of the StringLiteral is wrong.
Is something wrong with the StringLiteral implementation, or am I misunderstanding how it can be used?1 Reply
StringLiteral
is the type of Mojo string literals, and does not have a stable ABI representation. It should not be used for FFI.
Pointer[Int8]
is probably the right type for FFI. But after you've got the pointer, there are easier ways to interact with it that don't require copying. If you have a Pointer[Int8]
named p
, you can easily convert it to a StringRef
with StringRef(p)
. StringRef
is easy to interact with and works with many APIs. If you do want to copy it into a String
, that becomes trivial as well: String(StringRef(p))
.