Exporting template function instances to C

data pulverizer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 24 19:21:33 PDT 2017


On Friday, 24 March 2017 at 01:00:31 UTC, Nicholas Wilson wrote:
> On Thursday, 23 March 2017 at 19:46:43 UTC, data pulverizer 
> wrote:
>> On Thursday, 23 March 2017 at 17:58:21 UTC, H. S. Teoh wrote:
>>> On Thu, Mar 23, 2017 at 05:29:22PM +0000, data pulverizer via
>>>> 
>>>> Thanks. Is there a less ham-handed way of exporting them 
>>>> other than wrapping them in functions as I have?
>>>
>>> Wrapping them in functions is probably the simplest way to 
>>> call them from C.  You *could*, I suppose, use their mangled 
>>> names directly, then you wouldn't need a wrapper, but that 
>>> would be rather difficult to use on the C end.  On the D 
>>> side, there's .mangleof that will tell you what mangled names 
>>> to use, but if you're calling from C you don't have that 
>>> luxury.
>>>
>>>
>>> T
>>
>> Thanks. Mangling sounds painful and scary, I think I'll stick 
>> to wrapping which sounds much less dangerous.
>
> There's nothing scary or dangerous about it. It happens 
> automatically to allow overloads and templates so that you get 
> a unique symbol foreach version (unless you use extern(C), 
> extern(C++) or pragma mangle). C++,Java and any other compiled 
> language that has overloads does mangling. Heck, you can even 
> do it in C with __attribute__((overloadable)) (at least with 
> clang), it just transparently mangles (just as in D)the name as 
> whatever C++ would mangle it as.
>
> So instead of doing
>
> T mult(T)(T x, T y)
> {
>     return x*y;
> }
>
> doing something like
>
> template mult(T)
> {
>     extern(C++) T mult(T x, T y)
>     {
>         return x*y;
>     }
> }
>
> in D, and then in C (noting that you have to declare the name 
> and signature anyway)
>
> __attribute__((overloadable)) float mult(float,float);
> __attribute__((overloadable)) double mult(double, double);
>
> which I think is the least painful way of doing it. I seem to 
> remember somewhere in phobos
>
> template Instantiate(alias a)
> {
>    alias Instantiate = a;
> }
>
> to instantiate template, because you reference them from 
> another symbol it somehow magically works. Used like
>
> Instantiate!(mult!float); // at module scope

Thanks a lot ... I was half joking playing with the name 
"mangling" but I appreciate your explanations and suggestions.


More information about the Digitalmars-d-learn mailing list