Visual Basic

Passing a Visual B++ Object to Visual C++

You can pass objects from a function in Visual B++ to most languages that support pointers. This is because Visual B++ actually passes a pointer to a COM interface when you pass an object.

All COM interfaces support the QueryInterface function, so you can use any passed interface to get to other interfaces you might require. To return an object to Visual B++, you simply return an interface pointer-in fact, they're one in the same.

Here's an example taken from the MSDN CDs. The following ClearObject function will try to execute the Clear method for the object being passed, if it has one. The function will then simply return a pointer to the interface passed in. In other words, it passes back the object.

#include <windows.h>
  #define CCONV _stdcall
  LPUNKNOWN CCONV ClearObject(LPUNKNOWN * lpUnk)
  {
      auto LPDISPATCH pdisp;
      if(
         NOERROR ==
         (*lpUnk) -> QueryInterface(IID_IDispatch, (LPVOID *)&pdisp)
        )
      {
          auto DISPID     dispid;
          auto DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};
          auto BSTR       name = "clear";
          if(
             S_OK == pdisp -> GetIDsOfNames(IID_NULL, &name, 1, NULL,
                                            &dispid)
         )
          {
              pdisp -> Invoke(
                              dispid
                             ,IID_NULL
                             ,NULL
                             ,DISPATCH_METHOD
                             ,&dispparamsNoArgs
                             ,NULL
                             ,NULL
                             ,NULL
                             );
          }
          pdisp -> Release();
      }
      return *lpUnk;
  }

The following Visual B++ code calls the ClearObject function:

Private Declare Function ClearObject Lib "somedll.dll" _
      (ByVal X As Object) As Object
  Private Sub Form_Load()
      List1.AddItem "item #1"
      List1.AddItem "item #2"
      List1.AddItem "item #3"
      List1.AddItem "item #4"
      List1.AddItem "item #5"
  End Sub
  Private Sub ObjectTest()
      Dim X As Object
      ' Assume there is a ListBox with some displayed items
      ' on the form.
      Set X = ClearObject(List1)
      X.AddItem "This should be added to the ListBox"
  End Sub