C 如何使用LuaJIT';什么时候嵌入ffi模块?
我正在尝试将LuaJIT嵌入到C应用程序中。代码如下所示:C 如何使用LuaJIT';什么时候嵌入ffi模块?,c,lua,ffi,luajit,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; } i
#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;
}
-- 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'.
它报告如下错误:
#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;
}
-- 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” 在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;
}
如果在使用GCC的Linux下遇到未定义符号的问题,请注意让链接器通过将-rdynamic标志传递给GCC,将所有符号添加到动态符号表中:
g++-o应用程序源.cpp-rdynamic-I-我-伊利亚
<>对于那些试图用VC++(2012或更高版本)在Windows上进行这项工作的人,使用C++编译器:
- 使函数具有外部C链接,以便ffi可以使用
extern“C”{…}
- 使用
\uu declspec(dllexport)
- (可选)指定调用约定
,这不是必需的,因为默认情况下应该是这样,并且不可移植\uuu cdecl
- 将Lua头包装在
中,或者最好是外部“C”{include headers}
#include“Lua.hpp”