D callbacks in C functions

I am writing D2 bindings for Lua. This is in one of the Lua header files.

 typedef int (*lua_CFunction) (lua_State *L); 

I assume the equivalent D2 instruction would be:

 extern(C) alias int function( lua_State* L ) lua_CFunction; 

Lua also provides an api function:

 void lua_pushcfunction( lua_State* L, string name, lua_CFunction func ); 

If I want to press a D2 function, should it be extern (C) or can I just use the function?

 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? 

If I can use cfunc , why? I do not need to do anything similar in C++ . I can just pass the address of the C++ function to C , and everything just works.

+4
source share
2 answers

Yes, the function must be declared as extern (C) .

The calling convention of functions in C and D is different, so you must tell the compiler to use the C convention with extern (C) . I do not know why you do not need to do this in C ++.

See here for more information on interacting with C.

It's also worth noting that you can use the C style to declare function arguments.

+8
source

Yes, your typedef translation is correct. OTOH did you watch the htod tool ?

+1
source

Source: https://habr.com/ru/post/1305171/


All Articles