Passing an array from VC++ DLL to VB






4.23/5 (18 votes)
This article shows how to pass an array from a VC++ DLL to VB
Introduction
This article shows how to pass an array from a VC++ DLL to a VB application
The steps
- Create an ATL project named ArrayTry; Select DLL; Click Finish.
- Use ATL Object Wizard to add a simple object.
- Give the short name as myarray, click OK.
- The next step is to add a method which takes an array as well as returns it after filling it.
You can always add a method using the wizard but VC6 throws an error in this case as we are using
SAFEARRAY
. So we will do it manually which I think is more logical.
- So go to your .idl file and add the following below the UUID declaration of your interface
interface Imyarray : IDispatch { [id(1), helpstring("method LongArray")] HRESULT LongArray([in,out] SAFEARRAY(long)* pLarr); };
// Imyarray public: STDMETHOD(LongArray)(/*[in,out]*/ SAFEARRAY** pLarr);
STDMETHODIMP Cmyarray::LongArray(SAFEARRAY** pLarr) { long lElements; // number of elements in the array long iCount; HRESULT lResult; // return code for OLE functions // pointer to the elements of the array long *pArrayElements; long Larray[3] = {4,2,3};//existing array //checking if it is an one-dimensional array if ( (*pLarr)->cDims != 1 ) return(1); // checking if it is an array of longs if ( (*pLarr)->cbElements != 4 ) return(2); //Getting the number of elements of the array lElements = (*pLarr)->rgsabound[0].cElements; // locking the array before using its elements lResult=SafeArrayLock(*pLarr); if(lResult)return(lResult); // using the array pArrayElements=(long*) (*pLarr)->pvData; for (iCount=0; iCount<lElements; iCount++) pArrayElements[iCount] = Larray[iCount]; // releasing the array lResult=SafeArrayUnlock(*pLarr); if (lResult) return(lResult); return S_OK; }
Private Sub Command1_Click()
Dim x As New TRYARRLib.larray
Dim ArrayOfLongs(3) As Long 'Declare the array
x.LongArray ArrayOfLongs 'Get the array
For Counter = 0 To 2
'print the array contents
Debug.Print ArrayOfLongs(Counter)
Next
End Sub
That's It
Watch the results in the immediate window. Please write to me for any explanations/doubts , better way to do the same thing.