我正在开发一个项目,该项目采用 Lua 字符串并将其转换为 C 字符串——当然,一点也不困难。然而,当我尝试将函数的二进制表示形式(即通过调用 string.dump
生成的函数)转换为 C 字符串时,我遇到了麻烦。我无法读取整个字符串。
虽然这不是该项目的最终目标,但请考虑以下简单示例,其中我使用我注册的名为 chars
的 C 函数逐一打印字符串中的字符在 Lua 中使用:
static void chars(char* cp) {
char* pointer = cp;
while (*pointer) {
printf("%c\n", *pointer);
++pointer;
}
return;
}
static int lua_chars(lua_State* L) {
lua_len(L, 1);
size_t len = static_cast<size_t>(lua_tonumber(L, -1)) + 1;
lua_pop(L, 1);
if (len > 0) {
char* cp = static_cast<char*>(malloc(len));
strcat(cp, lua_tostring(L, 1));
chars(cp);
free(cp);
}
return 0;
}
从 Lua 脚本调用 chars
如下所示:
chars("Hello World!")
并且会一一打印出字符,每个字符后跟一个换行符。
现在讨论实际问题。考虑这个例子,我在 Lua 中声明一个函数,使用 string.dump
转储它,然后将该字符串传递给函数 chars
以单独打印出其字符:
local function foo()
print("foo")
return
end
local s = assert(string.dump(foo))
chars(s)
整个字符串s
,不是用我的函数chars
打印的,看起来像这样:
uaS?
xV(w@=stdin@A@$@&?&?printfoo_ENV
但是,chars
仅打印前五个字节:
u
a
S
(请注意,“u”之前应该有两行空格。)
我几乎可以肯定这是由于字符串中的空字符造成的,我认为这会干扰 lua_tostring
的功能。我遇到过用于读取 block 的 lua_Writer ,但我不知道如何使用/编码它。如何成功地将Lua堆栈上的整个字符串转换为C字符串?
最佳答案
I am almost certain that this is due to null characters within the string
是的,正是因为 Lua 字符串可以包含零。
which I think interferes with lua_tostring's functionality.
这是错误的。 lua_tostring()
按预期工作。只是strcat()
您使用的只会将数据复制到最接近的零字节。
如果需要复制字符串,请使用memcpy
,向其传递指向 Lua 字符串数据的指针和 Lua 字符串长度( lua_len
、 lua_rawlen
等)。
但仅仅为了打印,您甚至不需要复制任何内容。通过len
变量作为 chars()
的参数,并检查该长度而不是等待零字节。
关于c++ - 将 Lua 函数 block 转换为 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52602923/