Resources | developer.brewmp.com Resources | developer.brewmp.com

Developer

resources

Example - using a singleton in-process class

The c_appio2 example instantiates SimpleIOEcho twice, writes a random number to each instance, and then reads the data from each instance. To demonstrate the differences between singletons and non-singletons, the application instantiates both instances as a singleton or a non-singleton, depending on the key pressed.

The CIF for c_appio2 contains the following declaration for the singleton:

-- Declare a singleton class using AEECLSID_SimpleIOEcho class  
-- declared in c_service  
  
Singleton{  
   classid = AEECLSID_SimpleIOEchoSingle,  
   singled_id = AEECLSID_SimpleIOEcho,  
}

The c_appio2_HandleEvent() function calls c_appio2_CreateSimpleIO() with different parameters, depending on whether the key pressed was '1' or '2'. The c_appio2_CreateSimpleIO() function sets the classid to be instantiated to the singleton ClassID when the second parameter is TRUE, and to the non-singleton ClassID when it is FALSE, as shown below:

if(bSingleton){  
		//instances of SimpleIOEcho class will be created as a singleton  
		classid = AEECLSID_SimpleIOEchoSingle;  
	}else{  
		//instances of SimpleIOEcho class will be created as a non-singleton  
		classid = AEECLSID_SimpleIOEcho;  
	}  

c_appio2_CreateSimpleIO() then creates two instances of classid:

ERR_BAIL(IEnv_CreateInstance(me->piEnv, classid,(void **)&me->piSimpleIO1));

ERR_BAIL(IEnv_CreateInstance(me->piEnv, classid,(void **)&me->piSimpleIO2));

When classid is set to AEECLSID_SimpleIOEchoSingle, the classes are created as singletons and piSimpleIO1 and piSimpleIO2 are pointers to the same object. The data read from piSimpleIO1 is the same as the data written to piSimpleIO2 because the write to piSimpleIO2 overwrites the data written to piSimpleIO1. There is nothing to read from piSimpleIO2 because the data has already been read from piSimpleIO1. (Reading the data consumes it so that it cannot be read again.)

When classid is set to AEECLSID_SimpleIOEcho, the two instances of SimpleIOEcho are created as non-singletons and piSimpleIO1 and piSimpleIO2 are pointers to different objects. The data read from piSimpleIO1 is the same as the data written to piSimpleIO1, and the data read from piSimpleIO2 is the same as the data written to piSimpleIO2.