将数组从 VC++ DLL 传递到 VB






4.23/5 (18投票s)
本文演示了如何将数组从 VC++ DLL 传递到 VB
引言
本文档展示了如何从 VC++ DLL 向 VB 应用程序传递数组。
步骤
- 创建一个名为 ArrayTry 的 ATL 项目;选择 DLL;点击完成。
- 使用 ATL 对象向导添加一个简单的对象。
- 将短名称设置为 myarray,点击确定。
- 下一步是添加一个方法,该方法接收一个数组,并在填充后返回它。 您可以使用向导添加方法,但 VC6 在这种情况下会抛出错误,因为我们正在使用
SAFEARRAY
。 因此,我们将手动执行,我认为这更合乎逻辑。
- 因此,转到您的 .idl 文件,在接口的 UUID 声明下方添加以下内容:
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
就这些
在立即窗口中查看结果。 如果有任何解释/疑问,或更好的方法,请给我写信。