C函数中的D回调

def*_*ode 4 lua binding d

我正在D2为Lua 编写绑定.这是一个Lua头文件.

typedef int (*lua_CFunction) (lua_State *L);
Run Code Online (Sandbox Code Playgroud)

我假设等效的D2陈述是:

extern(C) alias int function( lua_State* L ) lua_CFunction;
Run Code Online (Sandbox Code Playgroud)

Lua还提供了api功能:

void lua_pushcfunction( lua_State* L, string name, lua_CFunction func );
Run Code Online (Sandbox Code Playgroud)

如果我想推送一个D2函数,它必须是extern(C)还是我可以使用该函数?

int dfunc( lua_State* L )
{
   std.stdio.writeln("dfunc");
}

extern(C) int cfunc( lua_State* L )
{
   std.stdio.writeln("cfunc");
}

lua_State* L = lua_newstate();
lua_pushcfunction(L, "cfunc", &cfunc); //This will definitely work.
lua_pushcfunction(L, "dfunc", &dfunc); //Will this work?
Run Code Online (Sandbox Code Playgroud)

如果我只能使用cfunc,为什么?我不需要做那样的事情C++.我可以将C++函数的地址传递给C一切正常工作.

Ber*_*ard 8

是的,该函数必须声明为extern (C).

C和D中函数的调用约定是不同的,因此您必须告诉编译器使用C约定extern (C).我不知道为什么你不必在C++中这样做.

有关与C接口的更多信息,请参见此处.

值得注意的是,您可以使用C样式声明函数参数.