struct opCast to void* and back

bearophile bearophileHUGS at lycos.com
Sun Apr 11 04:16:20 PDT 2010


Nrgyzer:

> Hello everyone,

Hello, this is a question fitter for the D.learn newsgroup.


> how can I cast a struct to void* and back to my struct? I have the following struct:

This is D2 code (yours was probably D1):


import std.stdio: writeln;

struct MyStruct {
    string structName;

    public string toString() {
        return structName;
    }

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

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

Note that struct names are written in with their first letter uppercase.
Using just a & you don't need that opCast.

Bye,
bearophile



More information about the Digitalmars-d mailing list