如何在嵌入式情况下使用LuaJIT的ffi模块?

我正在尝试将LuaJIT嵌入到C应用程序中。代码如下:

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

int barfunc(int foo)
{
    /*a dummy function to test with FFI*/
    return foo + 1;
}

int
main(void)
{
    int status, result;
    lua_State *L;
    L = luaL_newstate();

    luaL_openlibs(L);

    /* Load the file containing the script we are going to run */
    status = luaL_loadfile(L, "hello.lua");
    if (status) {
        fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
        exit(1);
    }

    /* Ask Lua to run our little script */
    result = lua_pcall(L, 0, LUA_MULTRET, 0);
    if (result) {
        fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
        exit(1);
    }

    lua_close(L);   /* Cya, Lua */

    return 0;
}

Lua代码如下:

-- Test FFI
local ffi = require("ffi")
ffi.cdef[[
int barfunc(int foo);
]]
local barreturn = ffi.C.barfunc(253)
io.write(barreturn)
io.write('\n')

它报告错误如下:

Failed to run script: hello.lua:6: cannot resolve symbol 'barfunc'.

我搜索了一下,发现关于ffi模块的文档真的很少。非常感谢。

原文链接 https://stackoverflow.com/questions/5919743

点赞
stackoverflow用户736296
stackoverflow用户736296

ffi 库需要 luajit,所以您必须使用 luajit 运行 Lua 代码。

从文档中可以得知:

"FFI 库紧密集成在 LuaJIT 中(不可用作单独的模块)。"

如何嵌入 luajit

请查看这里中的 "Embedding LuaJIT" 部分。

在 mingw 下,如果我在 barfunc 函数中添加如下代码:

__declspec(dllexport) int barfunc(int foo)

您的示例将成功运行。

在 Windows 下,luajit 作为 dll 进行链接。

2011-05-07 12:33:30
stackoverflow用户405517
stackoverflow用户405517

如 misianne 指出的那样,如果你使用 GCC,你需要导出该函数,你可以使用 extern 来实现:

extern "C" int barfunc(int foo)
{
    /* a dummy function to test with FFI */ 
    return foo + 1;
}

如果你在 GCC 下遇到未定义符号的问题,请注意让连接器将所有符号添加到动态符号表中,通过给 GCC 传递 -rdynamic 标志来实现:

g++ -o application soure.cpp -rdynamic -I... -L... -llua

2012-04-22 19:20:26
stackoverflow用户837113
stackoverflow用户837113

对于那些试图在 Windows 平台上使用 VC++ (2012 或之后版本) 编译器使其工作的人,需要注意以下几点:

  • 确保文件使用 .cpp 扩展名进行编译,这样可以用 C++ 进行编译

  • 使函数具有外部 C 链接,这样 ffi 就可以链接到它,使用 extern "C" { ... }

  • 通过 __declspec(dllexport) 从可执行程序中导出该函数

  • 可选地指定调用惯例 __cdecl,虽然默认应该是它,但不具有可移植性

  • 将 Lua 头文件包装在 extern "C" { include headers } 内,或者更好的方法是只用 #include "lua.hpp"

    #include "lua.hpp"
    
    extern "C" {
    __declspec(dllexport) int __cdecl barfunc(int foo) {
     return foo + 1;
    }}
    
2013-11-15 00:08:18