Problem with casting instance reference to void* and back.
Artur Skawina via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jul 27 06:27:43 PDT 2015
On 07/27/15 14:03, Vlad Leberstein via Digitalmars-d-learn wrote:
> Hi! My use case requires interaction with C API which in turn implies storing object instance reference as void *. I'm using gdc 4.9.2 and everything worked fine with "object -> void * -> object" conversion, but "object -> void * -> interface" failed. The stripped-down example is something like this:
>
> interface TestInterface {
> void testMethod();
> }
>
> class TestImpl : TestInterface {
> void testMethod() {
> writefln("TestImpl::testMethod\n");
> }
> };
>
> void testDispathcer(void *rawSelf) {
> auto self = cast(TestInterface) rawSelf;
> // nothing happens
> self.testMethod();
> }
>
>
> int main(string[] args) {
> auto t = new TestImpl();
> testDispathcer(cast(void *) t);
> return 0;
> }
> Is there any way to handle such situation without resorting to templating dispatcher with every *Impl type?
auto self = cast(TestInterface)cast(Object) rawSelf
[you should probably check for null, and consider using
a reinterpret-cast (`testDispathcer(*cast(void **)&t)`)
because a "normal" one can be overridden by the class,
sometimes accidentally]
artur
More information about the Digitalmars-d-learn
mailing list