gpt4 book ai didi

c - 如何在LuaJIT中打印固定的字符数组?

转载 作者:行者123 更新时间:2023-11-30 17:26:31 24 4
gpt4 key购买 nike

我正在尝试打印存储在固定数组中的以空结尾的字符串的内容。该数组在开始时被 memset 为零,然后填充以 null 结尾的字符串。我正在尝试打印该字符串。

这有效:

ffi.cdef[[
typedef struct _t
{
uint16_t i;
const char * name;
} MyStruct;
]]

ffi.cdef[[
MyStruct* Get();
]]

local myDll = ffi.load("myDll")
local x = myDll.Get()
print("Name: %s", x.name)

这会导致错误:

ffi.cdef[[
typedef struct _t
{
uint16_t i;
char name[25];
} MyStruct;
]]

ffi.cdef[[
MyStruct* Get();
]]

local myDll = ffi.load("myDll")
local x = myDll.Get()
print("Name: %s", x.name)

第二个产生此错误:

27: bad argument #2 to 'print' (cannot convert 'char [25]' to 'char (&)[25]')

注意:此帖子的代码是根据原始代码进行编辑的,未经编译。

看来我处理数组的方式不正确。正确的做法是什么?

最佳答案

您不能直接使用 print 函数打印 C 字符串。您需要先将其转换为 Lua 字符串,或者使用 C printf 函数

print("Name: ", ffi.string(x.name))

ffi.C.printf("Name: %s", x.name) -- Note: need to cdecl printf first

关于c - 如何在LuaJIT中打印固定的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26757953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com