Calling D functions from C

BCS ao at pathlink.com
Wed May 28 08:55:33 PDT 2008


Reply to Downs,

> BCS wrote:
> 
>> Reply to Downs,
>> 
>>> BCS wrote:
>>> 
>>>> Reply to Matthias,
>>>> 
>>>>> # extern (C) int myFunctionWrapper (char a, int b, char* c)
>>>>> # {
>>>>> #    return myFunction (a,b,c); // myFunction is a normal D
>>>>> function.
>>>>> # }
>>>> that deserves a template.
>>>> I guess I known what to do at lunch today.
>>> template Forward(string NAME) {
>>> mixin("extern(C) ReturnType!(&"~NAME~")
>>> c_"~NAME~"(ParameterTypeTuple!(&"~NAME~") p) {
>>> return "~NAME~"(p);
>>> }");
>>> }
>>> Untested, but should work.
>>> --downs
>>> 
>> maybe, I'd kind rather not use a mixin for that. (I avoid them
>> wherever I can) I'll take real a pass at it later.
>> 
>> On second look it seem the mixin is needed to make the name work but
>> it seem to be over kill for the rest
>> 
>> // untested
>> template Forward(alias NAME)
>> {
>> mixin(
>> "extern(C) ReturnType!(&NAME)
>> c_"~NAME.stringof~"(ParameterTypeTuple!(&NAME) p) { return NAME(p);}"
>> );
>> }
> Remember. stringof is not guaranteed to be in any sort of sane format.
> 
> For example, the above code would fail if it for some obscure reason
> contains spaces (or other invalid characters).
> 
> If you let the user pass a string, at least you know where the blame
> lies.
> 
> --downs
> 

// untested
template Forward(alias fn, char[] name)
{
mixin(
"extern(C)ReturnType!(&NAME)"~name~"(ParameterTypeTuple!(&fn) p){return fn(p);}"
);
}




More information about the Digitalmars-d-learn mailing list