Passing myself, a struct, as a C callback context
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Mar 30 08:32:03 PDT 2015
On 3/30/15 5:12 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm at gmx.net>"
wrote:
> On Monday, 30 March 2015 at 02:53:36 UTC, Paul O'Neil wrote:
>> I'm registering a callback with some C code. The simplified story is
>> here, but the actual code is on GitHub [1] at the end if you care.
>>
>> The call looks something like this.
>>
>> void register(void(*fp)(void*), void* context);
>>
>> I have a class that holds state for the callback and registers itself:
>>
>> final class Klass
>> {
>> void method()
>> {
>> register(callback_function, &this);
>> }
>> }
>
> `this` is already a reference. You're taking the address of that
> reference. A simple cast should work: `cast(void*) this`.
To build on this further, &this for a class is actually taking a local
stack reference, this is why it's not allowed.
And technically, cast(void*) this is dangerous in the general case
because opCast can be overridden. If you absolutely need to get a
pointer to a class reference, you would need to do this:
auto x = this;
auto p = &x;
For example, for a foolproof implementation of converting a class
reference to void *, you would need to do:
auto x = this;
auto p = *(cast(void **)&x);
I wonder if those who made this change thought of this problem?
-Steve
More information about the Digitalmars-d-learn
mailing list