Lua FFI指针处理

本文介绍了如何在Lua中正确调用C++代码,特别是涉及指针作为参数的情况。通过示例展示了错误的调用方式导致的类型转换问题,以及修正后的正确做法,包括使用ffi.typeof创建指针并进行操作,从而避免类型不匹配的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

最近需要在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

完美!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值