Unable to pass a D function member to a C callback

Alex sascha.orlov at gmail.com
Sat Nov 2 18:35:42 UTC 2019


On Saturday, 2 November 2019 at 17:49:09 UTC, Luh wrote:
> Hello,
>
> When trying to pass a D function to the C callback, the 
> compiler says:
>
> 'Error: cannot implicitly convert expression &this.onProcessCb 
> of type extern (C) bool delegate(const(short*) a, ulong b, 
> void* c) to extern (C) bool function(const(short*), ulong, 
> void*'
>
> because my function is member of a class (compiles when the 
> function is out of the class).
>
> Is there any way to say to solve this ?
> The wiki isn't very clear about the C callbacks:
> https://dlang.org/spec/interfaceToC.html#callbacks
>
> C code:
> ----
> typedef bool (*onProcessCallback)(const short*, size_t, void*);
> ----
>
>
> D Code:
> -----
> class Game
> {
> 	onProcessCallback m_onProcessCb;
> 	
> 	this()
> 	{
> 		m_onProcessCb = &onProcessCb; // Error here
> 	}
> 	
> 	void onProcess()
> 	{
> 		// ...
> 	}
>
> 	extern(C) bool onProcessCb(const short* a, size_t b, void* c)
> 	{
> 		onProcess();
> 		return true;
> 	}
> }
>
> private extern(C)
> {
> 	// Should call onProcess() when executed by the C lib
> 	alias onProcessCallback = bool function(const short*, size_t, 
> void*);
> }
> -----

This is because onProcessCb is a member of an object. Therefore, 
it carries also the information about the context, which includes 
e.g. all members of the class.

Due to this onProcessCb is a delegate, which is something 
different from a function, cf.
https://dlang.org/spec/function.html#closures

So, there is a type mismatch.



More information about the Digitalmars-d-learn mailing list