Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

lua - Running luajit object file from C

From the documentation: 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")

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", lua_tostring(L, -1));
    return 1;
  }
  return 0;
}

Shell commands:

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

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.

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...