> Advanced Programming Techniques > Using Callbacks > Implementing Callbacks in ILOG CPLEX with Concert Technology > Writing Callback Classes by Hand |
Writing Callback Classes by Hand |
INDEX PREVIOUS NEXT |
To implement your own callback for IloCplex
, first select the callback class corresponding to the callback you want implemented. From it derive your own implementation class and overwrite the virtual method main
. This is where you implement the callback actions, using the protected methods of the callback class from which you derived your callback or one of its base classes.
Next write a function that creates a new object of your implementation class using the environment operator new
and returning it as an IloCplex::Callback
handle object. Here is an example implementation of such a function:
IloCplex::Callback MyCallback(IloEnv env, IloInt num) { return (new (env) MyCallbackI(num)); } |
It is not customary to write such a function for Java, but new
is called explicitly for creating a callback object when needed. Once an implementation object of your callback is created (either with the constructor function in C++ or by directly calling the new
operator for Java), use it with IloCplex
by calling cplex.use
with the callback object as parameter. In C++, to remove a callback that is being used by a cplex
object, call callback.end
on the IloCplex::Callback
handle callback. In java there is no way of removing individual callbacks from your IloCplex
object. Instead, you can remove all callbacks by calling cplex.clearCallbacks
. Since Java uses garbage collection for memory management, there is nothing equivalent to the end
method for callbacks in the Java API.
One object of a callback implementation class can be used with only one IloCplex
object at a time. Thus, when you use a callback with more than one cplex
object, a copy of the implementation object is created every time cplex.use
is called except for the first time. In C++, the method IloCplex::use
returns a handle to the callback object that has actually been installed to enable calling end
on it.
To construct the copies of the callback objects in C++, class IloCplex::CallbackI
defines another pure virtual method:
which must be implemented for your callback class. This method will be called to create the copies needed for using a callback on different cplex
objects or on one cplex
object with a parallel optimizer.
In most cases you can avoid writing callback classes by hand, using supplied macros that make the process as easy as implementing a function. You must implement a callback by hand only if the callback manages internal data not passed as arguments, or if the callback requires eight or more parameters.
Copyright © 1987-2003 ILOG, S.A. All rights reserved. Legal terms. | PREVIOUS NEXT |