struct to/from void, object to/from void

Jason King jhking at airmail.net
Sun Apr 29 15:35:10 PDT 2012


I'm another of what seem to be legions of people trying to interface 
with OS stores that keep void * in c/c++.  My particular one is Windows 
TLSData, but for my example I don't need any Windows code, just D.

// this based on code I snagged from this group
// DMD 2.059 Win 7 Home Premium 64 bit.
import std.stdio: writeln;

struct MyStruct {
     string structName;

     public string toString() {
         return structName;
     }

     void* opCast() {
         return &this;
     }
}

class MyObject {
   string oname;

   this(string who) {
      oname = who;
   }

   public string toString() {
    return oname;
   }

   void* opCast() {
     return &this;
   }
}

void main() {
     MyStruct test = MyStruct("Example struct");
     MyStruct test2;
     void* temp1 = cast(void*)test;
     void* temp2 = &test;
     assert(temp1 == temp2);
     writeln(*cast(MyStruct*)temp1);
     test2 = *cast(MyStruct*)temp1;
     writeln(test2);

     auto o1 = new MyObject("Ok");
     MyObject o2;
     temp1 = cast(void*)o1;
     temp2 = &o1;
     //assert(temp1 == temp2);   // this is true for struct,
                                 // why not object?
     writeln(*cast(MyObject*)temp1);
     o2 = *cast(MyObject*)temp1;
     writeln(o2);
}

Structs seem to go both directions just fine, although something 
prettier than *cast(MyStruct*) would be nice for the return trip.

Objects seem to require a dedicated opCast and from my ng spelunking it 
appears opCast is frowned upon.

How would I do the to void* w/o opCast and is there a prettier way than
*cast(MyThing*) to get back the original "thing" from a void *?

If I get prettier code I'll  post it to the FAQ on the Wiki so that you 
gurus can quit dealing with the question so often.







More information about the Digitalmars-d-learn mailing list