基于Lua源码开发动态库供lua脚本使用

ops/2024/10/20 4:06:40/

通过require的方式可以加载动态库,然后脚本就可以使用库中提供的函数,一般过程如下:

比如有一个动态库名为:MyFirstLua.dll

则使用时:MyFirstLua = require("MyFirstLua")

导出的函数接口名称一定是 int luaopen_XXXX(lua_State* L)格式,且XXXX一定是导出库的文件名

#ifdef __cplusplus
extern "C" {
#endif#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"#ifdef __cplusplus
}
#endif#pragma comment(lib, "liblua.lib")static int export_add(lua_State *L) {if (lua_isinteger(L, 1) && lua_isinteger(L,2)) {lua_Integer n = lua_tointeger(L, 1);lua_Integer n2 = lua_tointeger(L, 2);lua_pushinteger(L, n+n2);}elselua_pushnil(L);return 1;
}static int export_print(lua_State* L)
{return 0;
}static const luaL_Reg exportLib[] = {{"add",export_add},{"print",export_print},{NULL, NULL}
};#ifdef __cplusplus
extern "C" {
#endif__declspec(dllexport) int luaopen_MyFirstLua(lua_State* L){luaL_newlib(L, exportLib);return 1;}#ifdef __cplusplus
}
#endif

上述代码导出一个MyFirstLua的dll库,并且导出luaopen_MyFirstLua函数接口。

在该函数中通过luaL_newlib的方式将函数注册导出到MyFirstLua表对象中。

通常导出函数形如:static int export_myfunction(lua_State* L),它的返回值代表这这个导出函数在脚本中应该返回多少个值


http://www.ppmy.cn/ops/56290.html

相关文章

【JavaScript】具有 iterable 接口的数据结构

具有 iterable 接口的数据结构指的是可以通过迭代器(Iterator)访问其成员的数据结构。在 JavaScript 中,具有 iterable 接口的数据结构包括数组(Array)、字符串(String)、Set、Map 等。这些数据…

扩散模型笔记2

Ref:扩散模型的原理及实现(Pytorch) 在扩散模型中,每一步添加的噪声并不是完全一样的。具体来说,噪声的添加方式和量在每一步是根据特定的规则或公式变化的。这里我们详细解释每一步添加噪声的过程。 正向过程中的噪声添加&…

JVM详解

目录 一、介绍 1.定义 2.组成划分 二、类加载系统 1.类的加载过程 2.类加载器 三、双亲委派机制 过程 双亲委派模型的优点 四、运行时数据区 五、对象的创建流程 六、垃圾回收机制 1.定义 1.1 引用计数法 1.2 可达性分析算法:GC Roots根 2.垃圾回收…

uniApp 封装VUEX

Vuex Store (index.js) import Vue from vue; import Vuex from vuex; import Cookies from js-cookie;Vue.use(Vuex);const saveStateKeys [vuex_user, vuex_token, vuex_demo];const initialState {vuex_user: { name: 用户信息 },vuex_token: Cookies.get(token) || ,vue…

【linux/shell】shell中实现函数重载

在 shell 脚本中,函数重载(Function Overloading)的概念与一些编程语言(如 Java 或 C#)中的函数重载不同。在这些编程语言中,你可以定义多个同名函数,只要它们的参数列表不同。然而,…

求函数最小值-torch版

目标:torch实现下面链接中的梯度下降法 先计算 的导函数 ,然后计算导函数 在处的梯度 (导数) 让 沿着 梯度的负方向移动, 自变量 的更新过程如下 torch代码实现如下 import torchx torch.tensor([7.5],requires_gradTrue) # print(x.gr…

Windows10系统下mysql5.6的安装步骤

1.下载mysql 下载地址:https://downloads.mysql.com/archives/community/ 在这里我们下载zip的包 2.解压mysql包到指定目录 3. 添加my.ini文件 # For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.6/en/server-configurat…

代码技巧专题 -- 使用策略模式编写HandleService

一.前言 最近项目有实习的同事加入,很多实习同事反映,看不懂项目中的一些使用了设计模式的代码,比如HandleService,Chains,Listener等。本篇就介绍一下策略模式在项目中的使用,也就是我们常在项目中看到的X…