www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - struct opCast to void* and back

reply Nrgyzer <nrgyzer gmail.com> writes:
Hello everyone,

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

struct myStruct {

	char[] structName;

	public char[] toString() {
		return structName;
	}

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

myStruct test = myStruct(); // ok
test.structName = "Example struct"; // ok
void* temp = cast(void*) test; // ok
writefln(cast(myStruct) temp); // failed


Thanks for solutions & help :).
Apr 11 2010
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
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
Apr 11 2010
prev sibling parent Robert Clipsham <robert octarineparrot.com> writes:
On 11/04/10 10:46, Nrgyzer wrote:
 Hello everyone,

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

 struct myStruct {

 	char[] structName;

 	public char[] toString() {
 		return structName;
 	}

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

 myStruct test = myStruct(); // ok
 test.structName = "Example struct"; // ok
 void* temp = cast(void*) test; // ok
 writefln(cast(myStruct) temp); // failed


 Thanks for solutions&  help :).

Try *cast(MyStruct*). In opCast you are returning &this, which is of type MyStruct* until it is implicitly cast to void*. In the writefln() you then cast it back to MyStruct*, and dereference it so you can use it. In your version you are trying to cast from a pointer to the struct to the actual struct, which is why it doesn't work.
Apr 11 2010