背景
最近需要在lua中调用C++代码,并且涉及到指针作为形参,懵逼了好久,最后在stackoverflow上找到了答案
C++代码(示例)
simple.cc
extern "C" void add(int * x, int * y)
{
*x = *x + *y;
}
编译代码为动态库
gcc -g -o libsimple.so -fpic -shared simple.cc
Lua代码(错误示范)
simple.lua
local ffi = require 'ffi'
local thresholding = ffi.load('simple')
ffi.cdef[[
void add(int * x, int * y);
]]
local x = 1
local y = 10
thresholding.add(x,y)
print(x)
print(y)
运行报错
luajit: simple.lua:11: bad argument #1 to 'add' (cannot convert 'number' to 'int *')
Lua代码(正确示范)
simple.lua
local ffi = require 'ffi'
local thresholding = ffi.load('simple')
ffi.cdef[[
void add(int * x, int * y);
]]
local x = 1
local y = 10
-- 创建int指针
local intPtr = ffi.typeof"int[1]"
local px = intPtr(x)
local py = intPtr(y)
thresholding.add(px,py)
-- 打印指针内容
print(px[0])
print(py[0])
输出
11
10
完美!