嵌入时如何使用LuaJIT的ffi模块?

时间:2011-05-07 07:37:13

标签: c lua ffi luajit

我正在尝试将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模块上的文档确实很少。非常感谢。

3 个答案:

答案 0 :(得分:9)

ffi库需要luajit,所以你必须用luajit运行lua代码。 来自doc: “FFI库紧密集成到LuaJIT中(它不作为单独的模块提供)”。

如何嵌入luajit? 在“嵌入LuaJIT”下查看http://luajit.org/install.html

如果我添加

,请运行你的示例
__declspec(dllexport) int barfunc(int foo)

在barfunc函数。

在Windows下,luajit链接为dll。

答案 1 :(得分:3)

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

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

如果您在Linux下使用GCC遇到未定义符号问题,请注意让链接器将所有符号添加到动态符号表中,方法是将 -rdynamic 标志传递给GCC:

  

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

答案 2 :(得分:2)

对于那些尝试使用VC ++(2012或更高版本)在Windows上使用C ++编译器进行此工作的人:

  • 确保使用.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;
    }}
    
相关问题