Call a function with a function pointer

Benjamin Thaut code at benjamin-thaut.de
Sun Oct 13 07:43:41 PDT 2013


Am 10.10.2013 17:45, schrieb Namespace:
> On Thursday, 10 October 2013 at 15:15:45 UTC, bearophile wrote:
>> Namespace:
>>
>>> You mean like this?
>>> ----
>>> void foo(T)(extern(C) void function(T*) func) {
>>>
>>> }
>>> ----
>>>
>>> That prints: Error: basic type expected, not extern
>>
>> In theory that's correct, in practice the compiler refuses that, it's
>> in Bugzilla, so try to define the type outside the signature (untested):
>>
>> alias TF = extern(C) void function(T*);
>>
>> void foo(T)(TF func) {}
>>
>> Bye,
>> bearophile
>
> /d917/f732.d(8): Error: basic type expected, not extern
> /d917/f732.d(8): Error: semicolon expected to close alias declaration
> /d917/f732.d(8): Error: no identifier for declarator void function(T*)

I found a possible workaround. Its ugly as hell, but at least it works 
until the bugs are fixed. The trick is to make a helper struct. Define 
the function you want within that, and then use typeof to get the type.


import std.stdio;

extern(C) void testFunc(int* ptr)
{
	*ptr = 5;
}

struct TypeHelper(T)
{
	extern(C) static void func(T*);
	alias typeof(&func) func_t;
}

void Foo(T)(TypeHelper!T.func_t func, T* val)
{
	func(val);
}

void main(string[] args)
{
	pragma(msg, TypeHelper!int.func_t.stringof);
	int test = 0;
	Foo!int(&testFunc, &test);
	writefln("%d", test);
}

-- 
Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list