extern(C) and name mangling

Mike Parker aldacron at gmail.com
Wed Dec 16 04:17:13 UTC 2020


On Tuesday, 15 December 2020 at 22:04:12 UTC, Dave P. wrote:
> I can’t find this in the spec, but from experimentation it 
> seems like extern(C) only affects name mangling of functions at 
> the top level scope. Thus extern(C) function templates would be 
> mangled differently, but still use the C calling convention. Is 
> this right?  I want to pass some templated functions as 
> function pointers to some C code and wanted to confirm that 
> would work (and that different versions would be mangled 
> differently).

Mangling does not play any role in passing and calling function 
pointers between D and C. It only plays a role in linking and 
loading. You can declare function pointers in D and C without any 
name whatsoever.

What matters is that both sides agree on the number and type of 
parameters accepted by the function that's pointed to, and that 
they both agree on the calling convention. I don't believe 
extern(C) has any effect on templated functions. However, the D 
calling convention is defined to be identical to the C calling 
convention on the host system for everything except Windows x86.

So theoretically, you should be able to pass a pointer to a 
templated free function to C as long as the types in the 
functions parameter list match those the C function expects. I 
don't know if I'd do that myself, though.

>
> Also, is there any way to say you want the C calling 
> convention, but don’t want C name mangling for top level 
> functions?

There's no such thing as C name mangling. C functions are *not* 
mangled (though some platforms do prepend an underscore to symbol 
names). What extern(C) does is to turn off D name mangling.

So what you're asking for is a way to retain the D name mangling 
on an extern C function. The way to do that is with 
`pragma(mangle, "new_name")`. To match the original D function 
mangling, declare the function first without extern(C) and print 
`func.mangleof`. Use that as the parameter to pragma(mangle).

I can't imagine any benefit you'd get from doing that, though.


More information about the Digitalmars-d-learn mailing list