11

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

4

3 回答 3

9

ffi 库需要 luajit,因此必须使用 luajit 运行 lua 代码。来自文档:“FFI 库紧密集成到 LuaJIT 中(它不能作为单独的模块使用)”。

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

如果我添加,在 mingw 下运行您的示例

__declspec(dllexport) int barfunc(int foo)

在 barfunc 函数中。

在 Windows 下,luajit 链接为 dll。

于 2011-05-07T12:33:30.470 回答
3

正如 misianne 指出的那样,您需要导出该函数,如果您使用的是 GCC ,则可以使用extern来完成:

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

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

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

于 2012-04-22T19:20:26.757 回答
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;
    }}
    
于 2013-11-15T00:08:18.660 回答