开发者

LuaJIT & FFI: How to use char* properly?

开发者 https://www.devze.com 2023-03-15 18:04 出处:网络
I have looked at the LuaJIT tutorial at: http://luajit.org/ext_ffi_tutorial.html I am trying to get more into Lua and wanted to see how easy it would be for me to call a simple \"lowercase\" function

I have looked at the LuaJIT tutorial at: http://luajit.org/ext_ffi_tutorial.html

I am trying to get more into Lua and wanted to see how easy it would be for me to call a simple "lowercase" function in a "libutility.so" I have written in C.

So here is the C function I want to call:

void lowercase(char* str){    
    int z;    
    for (z = 0; str[z]; z++){    
      str[z] = tolower(str[ z ]);    
    }    
}

So now I want to call this function from Lua...here is my code using LuaJIT's FFI

local ffi = require("ffi")
ffi.cdef[[
void lowercase(char* str);
]]
local utility = ffi.load("utility")    
local buf = ffi.new("char[?]", 11)
ffi.copy(buf, "HELLO WORLD")    
utility.lowercase(buf)
print("Result: ", #str)

The above code does not work...we开发者_如何学JAVAll I think it works until the LAST line of code above.

Can someone please give me some advise on how I can call this "lowercase" function and print out the result properly?


Try this:

local ffi = require("ffi")
ffi.cdef[[
void lowercase(char* str);
]]
local utility = ffi.load("utility")    
local buf = ffi.new("char[?]", "HELLO WORLD")
utility.lowercase(buf)
print("Result: ", ffi.string(buf))


I'm not at all sure what str is, but tolower returns it's value in place, so you really want to be printing buf.

0

精彩评论

暂无评论...
验证码 换一张
取 消