struct opCast to void* and back

Justin Spahr-Summers Justin.SpahrSummers at
Sun Apr 11 10:33:28 PDT 2010

On Sun, 11 Apr 2010 10:41:29 -0400, Nrgyzer <nrgyzer at> wrote:
> ...
> class MyClass {
> 	private static void function(void*) callBack;
> 	private static void* callBackValue;
> 	...
> 	static this() {
> 		MyStruct test = MyStruct();
> 		test.structName = "Struct name";
> 		callBack = &cb;
> 		callBackValue = &test;
> 	}

In this function, 'test' is allocated on the stack and therefore only 
exists for the duration of the function call. When the static 
constructor finishes, any pointers directed at 'test' are basically 
garbage and should never be used.

There are three workarounds:
1. Store 'test' in a place where it won't get destructed until you're 
done using it.
2. Allocate 'test' on the heap by using a pointer and 'new'.
3. Change MyStruct into a class so objects are allocated on the heap by 
default. This is probably the best solution for situations like this, 
especially given your explanation of what you're trying to do.

More information about the Digitalmars-d mailing list