如何将Terra Rawstring转换为LUA弦?

发布于 2025-02-09 12:09:42 字数 139 浏览 3 评论 0原文

我有一些返回char *的C代码,或者在Terra中RawString

如何将这种类型的值传递给LUA并将其用作普通字符串?

如果重要的话,将在堆上分配原肌(我不需要释放它)。

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

§对你不离不弃 2025-02-16 12:09:42

使用 luajit的ffi> ffi.string

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

- 字符串:

> 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

请注意,ffi.string()采用一个可选的长度参数,可以避免使用strlen对其进行计算,并且该字符串已在LUA(可能会泄漏内存)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文