【问题标题】:Unable to call a C function from Lua-lanes无法从 Lua 通道调用 C 函数
【发布时间】:2013-09-27 17:54:20
【问题描述】:

当尝试使用 Lua 通道从 Lua 模块调用 C 函数时,控件不会转移到“C”函数。 Lua 通道不能以线程方式与外部 C dll 一起工作有什么问题吗?

下面是代码sn-p

Lua 片段:

lanes.gen("*",func)
thread = func()
thread:join()

function func()
    foo() -- expected to print "Hello world", by 
          -- calling below C function,but not happening
end

C sn-p 用VS-2012编译成dll:

static int foo(lua_state *L)
{
   printf("Hello world\n")
}

【问题讨论】:

    标签: c lua lua-lanes


    【解决方案1】:

    如果你想在新线程中访问那个 C 函数,那么你必须在创建通道时以某种方式将它从主 lua 线程转移到新线程。您可以使用lua-lane docs 中的.required 来执行此操作。

    例如,假设你有这个简单的 foomodule:

    // foomodule.c
    // compiles to foomodule.dll
    #include <stdio.h>
    #include "lua.h"
    #include "lauxlib.h"
    
    static int foo(lua_State *L)
    {
      printf("Hello world\n");
      return 0;
    }
    
    int luaopen_foomodule(lua_State *L)
    {
      lua_pushcfunction(L, foo);
      lua_pushvalue(L, -1);
      lua_setglobal(L, "foo");
      return 1;
    }
    

    从你的 lua 脚本中:

    // footest.lua
    lanes = require 'lanes'.configure()
    
    function func()
      print("calling foo", foo)
      return foo()
    end
    
    thr = lanes.gen("*", {required = {'foomodule', }}, func)
    thr():join()
    

    一种可能的输出:

      calling foo     function: 0x003dff98
      Hello world
    

    【讨论】:

    • 感谢您的输入,通过从新通道加载 foomodule,我可以调用“C”函数
    【解决方案2】:

    您使用错误的车道。这是你需要做的:

    function func()
        foo() -- expected to print "Hello world", by 
              -- calling below C function,but not happening
    end
    
    local launcher = lanes.gen("*", func)
    thread = launcher()
    thread:join()
    

    应该没问题。

    【讨论】:

      猜你喜欢
      • 2014-09-01
      • 2013-02-19
      • 2015-12-30
      • 2022-01-04
      • 2015-07-14
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      相关资源
      最近更新 更多