-3

I am writing library that is supposed to initialize some data and return void pointer. Pointer is then used in C code. Inside library I want to use C++ class to initialize this data.

void *init()
{
    return new MyData();
}
void fini(void *d)
{
    MyData *m = reinterpret_cast<MyData *>(d);
    delete d;
}

This works while MyData is simple class without virtual methods. But now I want MyData to be an implementation of abstract class.

class Base // No virtual things
{
   int val;
};
class A : public Base // Abstract class
{
    virtual int x() = 0;
};
class B : public A // Implementation
{
    int x() {return val;}
};

If I then cast this class to void*, first 4 bytes of data will not reflect "val" variable of base class. Because of vtable maybe? Fine, I understood that this is wrong way to cast. Any suggestions? Something like

return static_cast<Base *>(new MyData);

seems to work but i also need to reconstruct MyData from void * and delete it properly. C program will only use values from Base part of MyData.

Here is alternative

void *init()
{
    return new MyData();
}
void fini(void *d)
{
    delete reinterpret_cast<MyData *>(d);
}
void *getbase(void *d)
{
    MyData *m = reinterpret_cast<MyData *>(d);
    return static_cast<Base *>(m);
}

but i'd like to avoid third function. Thanks and sorry for my english.

Sion0
  • 77
  • 7

1 Answers1

1
delete static_cast<A*>(static_cast<Base *>(d));

Worked in all tests. Thanks to geza.

Sion0
  • 77
  • 7