1

我想使用通道从 lua 调用 c 函数。

int initApp(lua_State *L) {
    lua_createtable(L, 0, 0);
    
    lua_pushcfunction(L, get_appinfo);
    lua_setfield(L, -2, "get_appinfo");
    
    lua_setglobal(L, "App");
    
    return 0;
}
local function thread1(n)
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    package.preload['App'] = function() return App end
    package.loaded['App'] = App
    local app = require 'App'
    print(app, app.get_appinfo) --table: 0x1234    function: 0x5678
    --(1)
    f = lanes.gen('*', {required = {'App'}}, thread1) --Lua Error: module 'App' not found: no field package.preload['App']...
    --(2)
    --f = lanes.gen('App', thread1) -- Bad library name: App
    a = f(1)
    sleep(1)
end

当我运行变体 (1) 时,我得到Lua Error: module 'App' not found: no field package.preload['App']...no file '/App.lua'.... 当我运行变体 (2) 时,我得到Bad library name: App.

如何调用App.get_appinfo()使用lanes?我可以将所有App函数移动到包中,但它必须从内存加载,而不是文件系统。我嵌入了所有 lua 包。

4

2 回答 2

0
  1. initApp例如,将 C 函数暴露给 Lua_G.init_App
    lua_pushcfunction(L, initApp);
    lua_setglobal(L, "init_App");
  1. 启动每个车道时将其作为参数传递
  2. 在车道内,调用init_App(作为第二个参数接收)-它将创建您的库
local function thread1(n, init_App)
    init_App()  -- create global table App in the current lane
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    local f = lanes.gen('*', thread1)
    a = f(1, init_App)  -- pass your module loader as argument
    sleep(1)
end
于 2021-11-26T18:45:28.943 回答
0

要调用 c 函数,我必须为on_state_createto传递一个函数lanes.configure

//c code
int init_App(lua_State *L) {
    lua_createtable(L, 0, 0);
    
    lua_pushcfunction(L, get_appinfo);
    lua_setfield(L, -2, "get_appinfo");
    
    lua_setglobal(L, "App");
    
    return 0;
}

int init(lua_State *L) {
    lua_pushcfunction(L, init_App);
    lua_setglobal(L, "init_App");
    luaL_dostring(L, "local lanes = require 'lanes'.configure{on_state_create=init_App}; local l = lanes.linda()");
    luaL_dostring(L, "startlanes()");
}

--lua code
local function thread1(n)
    return App.get_appinfo(n)
end

function startlanes()
    local lanes = require 'lanes'
    local f = lanes.gen('*', thread1)
    a = f(1)
    sleep(1)
    print(a[1])
end
于 2021-12-02T07:28:50.937 回答