struct opCast to void* and back

Nrgyzer nrgyzer at gmail.com
Sun Apr 11 08:02:10 PDT 2010


Robert Clipsham Wrote:

> On 11/04/10 15:41, Nrgyzer wrote:
> > I want to do the following:
> >
> > struct MyStruct {
> >
> > 	char[] structName;
> >
> > 	public char[] toString() {
> >
> > 		return structName;
> >
> > 	}
> > 	
> > }
> >
> > ...
> >
> > 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;
> > 	}
> > 	...
> > 	public void cb(void* value) {
> >
> > 		MyStruct temp = *((cast(MyStruct*) value));
> > 		writefln(temp);
> >
> > 	}
> >
> > }
> 
> Why the need for void* everywhere? Surely you could save the effort and 
> store it as a MyStruct?

Because I call MyClass.cb by using an other class... for example the Button-Class.

struct MyStruct {

        char[] structName;

        public char[] toString() {

                return structName;

        }
        
}

...

class MyClass {

	public static Button[] loadButtons() {
		
		Button[] buttons;
		
		for (int i=0; i < 10; i++) {
			
			MyStruct curStruct = MyStruct();
			curStruct.structName = .toString(i);

			buttons ~= new Button(cb, curStruct);

		}

		return buttons;

	}

        public static void cb(void* value) {

                MyStruct temp = *((cast(MyStruct*) value));
                writefln(temp);

        }

}

class Button {

        private static void function(void*) callBack;
        private static void* callBackValue;

	this(void function(void*) cB, void* cbValue) {

		callBack = cB;
		callBackValue = cbValue;

	}

	public void pressButton() {
		// This should call MyClass.cb
		callBack(callBackValue);

	}

}

For example... I click on a button on my OpenGL-gui, then I simply call the pressButton-method in my class Button which should call MyClass.cb with callBackValue which can be a value, class, struct or a similar datatype. To store different values/classes/structs... I cast all to a void-pointer. In this case I can use the Button-class in multiple situations.



More information about the Digitalmars-d mailing list