Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1448

Using VB6 Collections, Variants, & Byte Arrays in C++

$
0
0
This is vb6 specific so I am guessing this is probably the best place for it.

Sometimes you need to do a task in C/C++ and call it from VB6. Maybe its a library only available in C or you found some ready to use code. Transfer of simple types like strings or numbers is pretty straight forward, but what if you need to return a variable sized array of data elements? Things get tricky and go beyond standard C types.

The easiest solution is to dump the data to a file, or use vb6 call backs and have vb build up the array/collection for you. What i really wanted though was a way to pass a vb6 collection into a C function so that it could add arbitrary amounts of data. Searching the internet I couldnt find any examples of this. Luckily I finally had some spare time this weekend and was able to sort it out.

The sample looks deceptively simple. Figuring out the setup on what was required was a bit tricky. While there is allot going on behind the scenes automatically for us through the use of the smart pointers and the _variant_t type it actually ends up being very easy to use.

Vb example:
Code:

'we cant create a vba.collection in C, so we use a reference passed in from vb
Private Declare Sub addItems Lib "col_dll" (ByRef col As Collection)

Private Sub Command1_Click()

    Dim c As New Collection
    Dim x, tmp
   
    addItems c
    Me.Caption = c.Count & " items returned"
   
    For Each x In c
        tmp = tmp & x & vbCrLf
    Next
   
    Text1 = tmp
   
End Sub

C++ Dll Code
Code:

#include "msvbvm60.tlh"

void addStr(_CollectionPtr p , char* str){
        _variant_t vv;
        vv.SetString(str);
        p->Add(&vv.GetVARIANT());
}

void __stdcall addItems(_CollectionPtr *pColl)
{
#pragma EXPORT
       
        addStr(*pColl, "this is my string1");
        addStr(*pColl, "this is my string2");
        addStr(*pColl, "this is my string3");
        addStr(*pColl, "this is my string4");
}

So for the C portion, the tlh and tli files were generated by

#import "msvbvm60.dll" no_namespace

we then manually modified them to only include the collection object and we now import them manually. (they gave compile error as auto generated)

These files give us the smart pointer definition for the VB6 _CollectionPtr object. The VBA.Collection type can not be created by C++ code. So in order to use it we just pass in a live collection instance from our VB6 caller.

The demo app includes several methods designed to test for memory leaks, dangling pointers, corruption, and object ownership. This technique is passing on all fronts and looks good. The C project files are for VS 2008.
Attached Files

Viewing all articles
Browse latest Browse all 1448

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>