Unable to pass a D function member to a C callback

Luh null at null.null
Sat Nov 2 19:42:54 UTC 2019


On Saturday, 2 November 2019 at 18:31:28 UTC, Stefan Koch wrote:
> 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*);
>> }
>> -----
>
> you are missing a static in your member function's signature.
> The callback is not providing a this pointer.

My problem is, that the onProcess function should not be static 
because it uses a variable inside the class.

like:
-----
class Game
{
	private short[] m_a;
	
	void onProcess(short[] a)
	{
		m_a ~= a;
		// ...
	}

	extern(C) bool onProcessCb(const short* a, size_t b, void* c)
	{
		onProcess();
		return true;
	}
}
-----

So I think I just can't. :(


More information about the Digitalmars-d-learn mailing list