我正在尝试使用Lua FFI使用LuaJIT将一些文本附加到文件中,但我不是很了解C,所以我遇到了一些麻烦。这是代码:
local ffi = require "ffi"
ffi.cdef[[
typedef int __kernel_ssize_t;
typedef __kernel_ssize_t ssize_t;
ssize_t write(int fildes, const void *buf, size_t nbyte);
]]
local f = io.open("/tmp/test", "a+") -- Opening file in append mode
local message = "Hello World"
ffi.C.write(f, message, string.len(message))
f:close()
但是我收到以下错误:
luajit: test.lua:12: bad argument #1 to 'write' (cannot convert 'void *' to 'int')
stack traceback:
[C]: in function 'write'
c.lua:12: in main chunk
[C]: at 0x0100001490
答案 0 :(得分:3)
我已使用以下代码解决了此问题:
local ffi = require "ffi"
ffi.cdef[[
typedef struct {
char *fpos;
void *base;
unsigned short handle;
short flags;
short unget;
unsigned long alloc;
unsigned short buffincrement;
} FILE;
FILE *fopen(const char *filename, const char *mode);
int fprintf(FILE *stream, const char *format, ...);
int fclose(FILE *stream);
]]
local f = ffi.C.fopen("/tmp/test", "a+")
ffi.C.fprintf(f, "Hello World")
ffi.C.fclose(f)