tags:

views:

122

answers:

2

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 statement 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 push a D2 function does it have to 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 only use cfunc, why? I don't need to do anything like that in C++. I can just pass the address of a C++ function to C and everything just works.

+6  A: 

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

The calling convention of functions in C and D are different, so you must tell the compiler to use the C convention with extern (C). I don't know why you don't have to do this in C++.

See here for more information on interfacing with C.

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

Bernard
It's possible that C and C++ are *close enough* that it doesn't matter.
DK
As an educated guess, I think for C++, any function that can be passed as a function pointer to C (The type of the function pointer is definable in C) will have the same calling convention.
BCS
A: 

Yes, your typedef translation is correct. OTOH have you looked at the htod tool?

BCS