Let it breathe
Now we have a library without any objects in it. Let's add our first
object (in this tutorial, we will only use one object, but added more
objects works analogically to this).
Move
your mouse over the MyLib classes root node and press the right
mouse-button. From the context menu choose "New ATL Object...".
In the next dialog choose the "objects" category and mark "Simple Object" as object. Press next.
Enter
a short name for your object (this is VC++ internal, you won't see this
in your VB app). I choosed "MyObject". VC++ will create a C++ class
names "CMyObject" from this COM-object. You could rename it, but we
will keep that name. You can specify the name of the CoClass at the
"CoClass" textbox. This will be the name of the COM-object as it
appears in the interface description. That means, this will be the name
of the object as you will see it in VB. Press "OK".
Here
is our object. As you see, it only has a constructor "CMyObject()" and
a interface "IMyObject". We will now add a function to our object. This
function should implement a loop, that adds x times a value to 0 and
then return the result. So this is a multiply realised by adding a
value. Later on we will use this function to measure the time that our
C++ function takes and compare it with VB.
The function should get 2 parameters.
- lValue as Long ' this is the value that is always added
- lCount as Long ' lCount times will the loop be executed
-
- rc as Long ' this should be the return value
Move your mouse over the interface node and right-click it. From the popup-menu choose the option "Add Method...".
Give
our method a name. I took "Calculate". This will also the name as you
will see it in the VB IDE. Type in our parameter list:
- long lvalue, long lcount, [out, retval] long* rc
O.K.,
I think the first 2 parameters are clear if you understand a littlebit
about C++. But why is there a third input parameter with such a funny
declaration? And where is our return parameter?
COM interface
functions always have the same format: They have a variable list of
parameters and also return a return-code as HRESULT. If the HRESULT
isn't S_OK the function failed and a COM error is raised. The VC++ IDL
(Interface Decription Language) compiler interpretes the parameters
[out, retval] and declares the parameter as an out-parameter and as the
(one and only) return value. You must pass the variable as a pointer,
because this is the only way to get data out of this function. That's
the whole magic.
This is what our function looks like. Double-click it and the VC++ IDE
brings you directly to the source of that function. Enter the following
code:
- STDMETHODIMP CMyObject::Calculate( long lvalue, long lcount, long *rc)
- {
- long lresult = 0;
- for ( long i = 0; i < lcount; i++)
- {
- lresult = lresult + lvalue;
- }
-
- *rc = lresult;
-
- return S_OK;
- }