栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Lua FFI指针处理

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Lua FFI指针处理

背景

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

完美!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942675.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号