[英]How to use LuaJIT's ffi module when embedding?
我正在嘗試將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模塊上的文檔確實很少。 非常感謝。
ffi庫需要luajit,所以你必須用luajit運行lua代碼。 從文檔:“FFI庫緊密集成到LuaJIT(它不作為單獨的模塊提供)”。
如何嵌入luajit? 在“嵌入LuaJIT”下查看http://luajit.org/install.html
在mingw下你的例子運行,如果我添加
__declspec(dllexport) int barfunc(int foo)
在barfunc函數。
在Windows下,luajit鏈接為dll。
正如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應用soure.cpp -rdynamic -I ... ... -L -llua
對於那些嘗試使用VC ++(2012或更高版本)在Windows上進行此工作的人,使用C ++編譯器:
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; }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.