4

最近は学習に 5.2 を使用しています。

ステップ 1、lua 用の ac モジュールをビルドします。

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

static int add(lua_State *L) {
    int x = luaL_checkint(L, -2);
    int y = luaL_checkint(L, -1);
    lua_pushinteger(L, x + y);
    return 1;
}

static const struct luaL_Reg reg_lib[] = {
    {"add", add}
};

int luaopen_tool(lua_State *L) {
    luaL_newlib(L, reg_lib);
    lua_setglobal(L, "tool");
    return 0;
}

これをコンパイルして liblua.a にリンクしましたが、"require("tool") tool.add(1, 2)" のような lua スクリプトでうまく動作することを確信しています。

ステップ 2、次のように、ステップ 1 で c モジュールを要求する別の C プログラムを作成します。

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

int main(int argc, char* const argv[]) {
    lua_State *L = luaL_newstate(); 
    luaL_requiref(L, "base", luaopen_base, 1);
    luaL_requiref(L, "package", luaopen_package, 1);
    lua_getglobal(L, "require");
    if (!lua_isfunction(L, -1)) {
        printf("require not found\n");
        return 2;
    }
    lua_pushstring(L, "tool");
    if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
        printf("require_fail=%s\n", lua_tostring(L, -1));
        return 3;
    }
    lua_getfield(L, -1, "add");
    lua_pushinteger(L, 2);
    lua_pushinteger(L, 3);
    lua_pcall(L, 2, 1, 0);
    int n = luaL_checkint(L, -1);
    printf("n=%d\n", n);
    return 0;
}

私も liblua.a でコンパイル & リンクしますが、実行するとエラーが発生します: "require_fail=multiple Lua VMs detected"

誰かのブログによると、lua5.2 では、c モジュールと c ホスト プログラムの両方を動的にリンクする必要がありますが、静的にリンクする必要はありません。

同じ問題を抱えている人がいますか、それとも私のコードに何か問題がありますか?

知らせ:

この問題は、メイン プログラムを -Wl,-E でコンパイルすることで解決されました。ご協力ありがとうございます ^^.

4

1 に答える 1

5

liblua.a から .so を作成するときは、C モジュールを liblua.a とリンクしないでください。例については、Lua ライブラリの私のページを参照してください: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/。liblua.a をメイン プログラムに静的にリンクできますが-Wl,-E、リンク時に追加してそのシンボルをエクスポートする必要があります。これが、Lua インタープリターが Linux に組み込まれている方法です。

于 2013-01-08T19:51:29.230 に答える