0

I have some C code that returns char *, or rawstring in Terra.

How can I pass a value of this type to Lua and use it as a normal string?

If it matters, the rawstring is allocated on the heap (and I won't need to free it).

Renato
  • 12,940
  • 3
  • 54
  • 85

1 Answers1

1

Use LuaJIT's ffi.string function:

> terra terrastring()
>>   return "hello from Terra"
>> end
> print(terrastring())
cdata<char *>: 0x0e03c050
> print(ffi.string(terrastring()))
hello from Terra

And to prove it works even with non-literal Strings:

> C = terralib.includecstring "#include <stdlib.h>"
> terra cstr()
>>  var str = [&int8](C.calloc(4, sizeof(int8)))
>>  str[0],str[1],str[2],str[3] = 104,101,121,0
>>  return str
>> end
> print(cstr())
cdata<char *>: 0x0e03c000
> ffi = require 'ffi'
> print(ffi.string(cstr()))
hey

Notice that ffi.string() takes an optional length parameter, which may be handy to avoid using strlen to compute it, and that the string is interned in Lua (which may leak memory).

Renato
  • 12,940
  • 3
  • 54
  • 85