pragma(mangle) on types

Moritz Maxeiner via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 11 06:14:39 PDT 2017


On Tuesday, 11 July 2017 at 07:28:59 UTC, Jacob Carlborg wrote:
> In D it's possible to use pragma(mangle) on a function to set 
> the name that will actually end up in the binary. This is 
> useful if you need to link to a C function that uses the same 
> name as a keyword in D.
>
> I think we need the same thing for types as well. This is 
> important when binding to C++ and Objective-C.
>
> [...]

We definitely need to address this, as the obvious workaround is 
atrocious:

---
// Struct as declared when interfacing with C
struct IntC
{
     int i;
}

// Wrapping struct (matching the name declared in C++) to be used 
for C++ function stubs
struct IntCC { IntC v; }
extern(C++) void foo(IntCC integer);

// D wrapper calling into the stubs
void foo(IntC integer)
{
     foo(IntCC(integer));
}

---

I think type pragmas would be a reasonable addition, but I'm as 
of yet not convinced they will actually help much in this case, 
because they define what the final symbol name will be in object 
code and in C++ the symbol mangling is left up to the compiler 
[1].
If you wrote code like this:

---
pragma(mangle, "Int")
struct IntC
{
     int i;
}

extern(C++) void foo(IntC integer);
---

you would be stating that the mangled symbol of "IntC" in the 
object code generated for C++ shall be "Int".
This may usually be the case, but AFAIK there's no guarantee that 
your C++ compiler will do so.
In the workaround shown above things "work" because we are merely 
specifying the symbols (unmangled) name and letting the D 
compiler worry about choosing the appropriate C++ mangling, but 
with pragma(mangle) we would then have to litter the declaration 
with C++ mangling schemes, i.e.

---
version (CCManglingSchemeA)
{
     pragma(mangle, "ManglingAInt");
     struct IntC {...}
}
else version (CCManglingSchemeB)
{
     pragma(mangle, "ManglingBInt");
     struct IntC {...}
}
---

Manually matching C++ mangling schemes doesn't strike me as the 
best option, but I also don't know how to do it better (other 
than the workaround above).

[1] 
https://en.wikipedia.org/wiki/Name_mangling#Standardised_name_mangling_in_C.2B.2B


More information about the Digitalmars-d mailing list