Created
May 10, 2019 12:03
-
-
Save omigafu/c6f8c1f5908be3b61eb587af2682beac to your computer and use it in GitHub Desktop.
luajit ffi使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ffi = require("ffi") | |
local t = {1, 2, 3} -- array of floating point numbers | |
-- lua数组 t 也可以是int,float | |
-- ffi.new("float[?]", #t, t) new一个cdata,float数组,大小是#t:3,初始化用t | |
-- ffi.string 当第二个参数有的时候,第一个参数返回的指针类型是变成了void。(可能会导致字节序问题) | |
-- 如果第二个参数没有的话,第一个指针会转换成char*,并且当遇到/0的时候截断,字符串长度是由strlen()确定 | |
local str = ffi.string(ffi.new("float[?]", #t, t), 4 * #t) | |
print(#t) | |
print(str) | |
print(#str) | |
-- ffi.new("char[?]", #str, str) 表示将str转成字节数组,返回char*指针,强制转换为指向float类型的指针 | |
local ptr = ffi.cast("float*", ffi.new("char[?]", #str, str)) | |
local t = {} | |
-- ptr[1]表示指针指向的第一个float | |
for _ = 1, 3 do | |
t[#t + 1] = ptr[#t] | |
end | |
for k,v in pairs(t) do | |
print(k,v) | |
end | |
-- For 8-byte doubles, replace float with double and 4 with 8 | |
===== | |
3 | |
?@@@ | |
12 | |
1 1 | |
2 2 | |
3 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment