简体   繁体   English

将lua共享对象编译为嵌入式c

[英]compile lua shared object into embeded c

i have this code ( zstring.c ) 我有此代码( zstring.c

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <string.h>

static int zst_strlen(lua_State *L)
{
    size_t len;
    len = strlen(lua_tostring(L, 1));
    lua_pushnumber(L, len);
    return 1;
}

int luaopen_zstring(lua_State *L) 
{
    lua_register(L,"zst_strlen", zst_strlen);
    return 0;
}

and this is my lua embedded 这是我嵌入的lua

int main (){
    L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L, "test.lua");
    lua_close(L);
    return 0;
}

i do not want compile zstring.c to zstring.so object 我不想编译zstring.czstring.so对象

i want zstring.c compile into my embedded lua then i can call zstring from test.lua and use it 我想zstring.c编译到我的嵌入式lua的话,我可以叫zstringtest.lua ,并用它

how to do it? 怎么做?

You can accomplish this by including the zstring source file then calling luaopen_zstring after initializing Lua: 您可以通过包含zstring源文件,然后在初始化Lua之后调用luaopen_zstring来完成此操作:

#include "zstring.c"

int main (){
    L = luaL_newstate();
    luaL_openlibs(L);
    lua_pushcfunction(L, luaopen_zstring);
    lua_call(L, 0, 0);
    luaL_dofile(L, "test.lua");
    lua_close(L);
    return 0;
}

It should be noted that even if you do not want to generate a shared library, you can still create an object file for zstring (by using the -c flag with gcc , for example). 应该注意的是,即使您不想生成共享库,仍然可以为zstring创建目标文件(例如,将-c标志与gcc一起使用)。 You can then link that object file with your main source. 然后,您可以将该对象文件与您的主要源链接。

The steps for doing this are roughly: 大致的步骤如下:

  1. Compile zstring.c to an object file (eg gcc -c -o zstring.o zstring.c ) zstring.c编译为目标文件(例如gcc -c -o zstring.o zstring.c
  2. Create a header file named zstring.h : 创建一个名为zstring.h的头文件:

     #ifndef ZSTRING_H #define ZSTRING_H int luaopen_zstring(lua_State *L); #endif 
  3. Include the header in your main source file: 将标头包含在您的主源文件中:

     #include "zstring.h" int main (){ L = luaL_newstate(); luaL_openlibs(L); lua_pushcfunction(L, luaopen_zstring); lua_call(L, 0, 0); luaL_dofile(L, "test.lua"); lua_close(L); return 0; } 
  4. Compile the main file with the zstring.o object file linked (eg gcc -o myprogram main.c zstring.o ) 使用链接的zstring.o对象文件编译主文件(例如gcc -o myprogram main.c zstring.o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM