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

jag*_*ttt 11 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;
}
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

它报告错误如下:

Failed to run script: hello.lua:6: cannot resolve symbol 'barfunc'.
Run Code Online (Sandbox Code Playgroud)

我四处搜索,发现ffi模块上的文档确实很少.非常感谢.

mis*_*nne 9

ffi库需要luajit,所以你必须用luajit运行lua代码.从文档:"FFI库紧密集成到LuaJIT(它不作为单独的模块提供)".

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

在mingw下你的例子运行,如果我添加

__declspec(dllexport) int barfunc(int foo)
Run Code Online (Sandbox Code Playgroud)

在barfunc函数.

在Windows下,luajit链接为dll.