从 C 运行 luajit 目标文件 [英] Running luajit object file from C

查看:23
本文介绍了从 C 运行 luajit 目标文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档:http://luajit.org/running.html

luajit -b test.lua test.obj                 # Generate object file
# Link test.obj with your application and load it with require("test")

但是没有解释如何做这些事情.我猜他们假设任何使用 Lua 的人也是 C 程序员,而我不是这样!我能得到一些帮助吗?以海湾合作委员会为例.

But doesn't explain how to do these things. I guess they're assuming anyone using Lua is also a C programmer, not the case with me! Can I get some help? GCC as an example.

除了 C 字节数组头之外,我也想做同样的事情.我也找不到这方面的文档.

I would also like to do the same thing except from the C byte array header. I can't find documentation on this either.

luajit -bt h -n test test.lua test.h

这会创建头文件,但我不知道如何从 C 中运行它.谢谢.

This creates the header file but I don't know how to run it from C. Thanks.

推荐答案

ma​​in.lua

print("Hello from main.lua")

app.c

#include <stdio.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main(int argc, char **argv)
{
  int status;
  lua_State *L = luaL_newstate();
  luaL_openlibs(L);
  lua_getglobal(L, "require");
  lua_pushliteral(L, "main");
  status = lua_pcall(L, 1, 0, 0);
  if (status) {
    fprintf(stderr, "Error: %s
", lua_tostring(L, -1));
    return 1;
  }
  return 0;
}

Shell 命令:

luajit -b main.lua main.o
gcc -O2 -Wall -Wl,-E -o app app.c main.o -Ixx -Lxx -lluajit-5.1 -lm -ldl

用 LuaJIT 包含和库目录替换 -Ixx-Lxx.如果您已将其安装在 /usr/local(默认值)中,那么大多数 GCC 安装将在没有这两个选项的情况下找到它.

Replace -Ixx and -Lxx by the LuaJIT include and library directories. If you've installed it in /usr/local (the default), then most GCC installations will find it without these two options.

第一条命令将 Lua 源代码编译为字节码并将其嵌入到目标文件 main.o 中.

The first command compiles the Lua source code to bytecode and embeds it into the object file main.o.

第二个命令编译并链接最小的 C 应用程序代码.请注意,它也链接到嵌入的字节码中.-Wl,-E 是强制性的(在 Linux 上)从可执行文件中导出所有符号.

The second command compiles and links the minimal C application code. Note that it links in the embedded bytecode, too. The -Wl,-E is mandatory (on Linux) to export all symbols from the executable.

现在将原来的 main.lua 移开(以确保它真正运行嵌入的字节码而不是 Lua 源代码文件),然后运行您的应用程序:

Now move the original main.lua away (to ensure it's really running the embedded bytecode and not the Lua source code file) and then run your app:

mv main.lua main.lua.orig
./app
# Output: Hello from main.lua

这篇关于从 C 运行 luajit 目标文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆