Using a delegate when interfacing with C
Marco Cosentino via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 5 15:18:56 PDT 2014
Hi,
I'm quite new to D and I'm not able to find out what I'm doing
wrong.
Consider the following code:
class ClientImplementation {
private ProcessDelegate processDelegate;
void setProcessDelegate(ProcessDelegate deleg) {
this.processDelegate = deleg;
extern(C) ProcessCallback callback = function int(NFrames
nframes, void* data) {
auto client = *(cast(ClientImplementation*) data);
return client.processDelegate(nframes);
};
this.setProcessCallback(callback, cast(void *) &this);
}
In my D wrapper for a C API I want to use delegates. The C API
accepts a callback which has a generic void* parameter which can
be specified when setting the callback (it will be stored and
passed in the callback when it gets called... a common pattern in
C APIs).
So I want to use it to make delegates possible.
The problem with this approach is that I get a segmentation fault
on the line:
auto client = *(cast(ClientImplementation*) data);
as soon as the callback is called the first time.
The callback is called in another thread (but this shouldn't be a
problem since ClientImplementation is a class and therefore
instances are created in the heap).
Can somebody help me in figuring out why this happens?
I also tried unsuccesfully
auto client = cast(ClientImplementation*) data;
More information about the Digitalmars-d-learn
mailing list