在 C 端嵌入 Lua 个模块
Embedding Lua modules on C side
我想为用户提供几个自定义函数来使用,但隐藏它的实现以将其作为简单的 DLL 提供。
所以用户只需 link dll 和插件按原样工作。在 C 端动态声明了几个表、整数等,但是从 C 声明 "classes"、table-oriented 函数会使代码不可读。
例如,有没有办法将 Lua 模块嵌入到 header 中,并预加载它以便主脚本用户加载 luaL_loadfile可以访问吗?
我当然可以 dirty-hack 通过将代码插入用户的脚本来实现它,但这似乎是个坏主意。
Is there a way to embed Lua module in a header, for example, and preload it so the main script user loads with luaL_loadfile will be able to access it?
是的。您可以使用 bin2c.lua(或底部列出的任何替代方法)。
这是来自名为 fakeredis.c 的项目的 real-world 示例:
Makefile
包含一个专用目标,它创建一个 header,由要嵌入的各种模块的 Lua 字节码组成:
fklua.h:
@echo "converting lua -> C..."
@./lua2c.sh
(幕后 lua2c.sh
使用 bin2c.lua
)
例如,项目包含一个名为 fmtreply.lua 的模块。转换后,此模块被简单地定义为字节数组:
/* fklua.h */
/* this is the name of the main function the module exposes */
#define FK_LUA_FMTREPLY "_fmtreply"
/* this is the byte code of the module obtained with `bin2c.lua` */
static const unsigned char fk_lua_fmtreply[]={45, 45, 32, ...};
然后模块通过 luaL_loadbuffer
(see here and there 显式加载到主库中以获得更多详细信息。
我想为用户提供几个自定义函数来使用,但隐藏它的实现以将其作为简单的 DLL 提供。
所以用户只需 link dll 和插件按原样工作。在 C 端动态声明了几个表、整数等,但是从 C 声明 "classes"、table-oriented 函数会使代码不可读。
例如,有没有办法将 Lua 模块嵌入到 header 中,并预加载它以便主脚本用户加载 luaL_loadfile可以访问吗?
我当然可以 dirty-hack 通过将代码插入用户的脚本来实现它,但这似乎是个坏主意。
Is there a way to embed Lua module in a header, for example, and preload it so the main script user loads with luaL_loadfile will be able to access it?
是的。您可以使用 bin2c.lua(或底部列出的任何替代方法)。
这是来自名为 fakeredis.c 的项目的 real-world 示例:
Makefile
包含一个专用目标,它创建一个 header,由要嵌入的各种模块的 Lua 字节码组成:
fklua.h:
@echo "converting lua -> C..."
@./lua2c.sh
(幕后 lua2c.sh
使用 bin2c.lua
)
例如,项目包含一个名为 fmtreply.lua 的模块。转换后,此模块被简单地定义为字节数组:
/* fklua.h */
/* this is the name of the main function the module exposes */
#define FK_LUA_FMTREPLY "_fmtreply"
/* this is the byte code of the module obtained with `bin2c.lua` */
static const unsigned char fk_lua_fmtreply[]={45, 45, 32, ...};
然后模块通过 luaL_loadbuffer
(see here and there 显式加载到主库中以获得更多详细信息。