从C运行luajit对象文件 [英] Running luajit object file from C

查看:186
本文介绍了从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.

推荐答案

main.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\n", 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

替换 -Ixx -Lxx 由LuaJIT包括和库目录。如果你已经在的/ usr /本地(默认)安装了它,那么大多数海湾合作委员会的安装会发现它没有这两个选项。

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的源$ C ​​$ C到字节code和它嵌入到目标文件 main.o中

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

第二个命令编译和链接的最小C应用程序code。请注意,它连接在嵌入式字节code,太。在 -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离开(以确保它的真正运行嵌入式字节code,而不是Lua的源$ C ​​$ C文件),然后运行你的应用程序:

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天全站免登陆