gpt4 book ai didi

c - 无法从 Lua-lanes 调用 C 函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:32 25 4
gpt4 key购买 nike

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

下面是代码片段

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

使用 VS-2012 编译成 dll 的 C 片段:

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

最佳答案

如果您希望在新线程中访问该 C 函数,那么您必须在创建 channel 时以某种方式将其从主 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

关于c - 无法从 Lua-lanes 调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com