VARIANT导出/导入C ++ DLL SAFEARRAY

时间:2017-05-02 08:43:38

标签: c++ vba dll variant safearray

我知道这个话题很受欢迎。但是,我想解决一个简单的问题...我的目标是在C ++中创建一个能够从VB(Excel或其他程序)导入和导出数据矩阵的DLL。我在一些博客中读到,常见的方法是使用SAFEARRAY。

所以,我创建了以下C ++代码:

VARIANT _stdcall ReadArrayVBA_v1(VARIANT *Input0) {

    double dm = 0, rm = 0;

    //OUTPUT DATA DEFINITION
    VARIANT v;
    SAFEARRAYBOUND Dim[1];
    Dim[0].lLbound = 0; Dim[0].cElements = 4;
    v.vt = VT_R8;
    v.parray = SafeArrayCreate(VT_R8, 1, Dim);
    //==============================================

    SAFEARRAY* pSafeArrayInput0 = NULL; //Define a pointer SAFEARRAY Type
    pSafeArrayInput0 = *V_ARRAYREF(Input0); 

    long lLBound = -1, lUBound = 1; //Preset dimension
    SafeArrayGetLBound(pSafeArrayInput0, 1, &lLBound); 
    SafeArrayGetUBound(pSafeArrayInput0, 1, &lUBound);

    long CntElements = lUBound - lLBound + 1;
    long Index[1];
    for (int i=0; i<CntElements; i++){

        Index[0] = i;
        SafeArrayGetElement(pSafeArrayInput0, Index, &dm);

        rm = dm + 1;

        SafeArrayPutElement(v.parray, Index, &rm);

}

return v;

}

它编译并以下列方式从VBA Excel调用:

Private Declare Function ReadArrayVBA_v1 Lib "[PATH]\VARIANTtest.dll" (ByRef Input0 As Variant) As Variant

Sub VBACall()
    Dim InputR0(1 To 4) As Variant
    Dim vResult1 As Variant

    InputR0(1) = 2
    InputR0(2) = 20
    InputR0(3) = 200
    InputR0(4) = 240

   vResult1 = ReadArrayVBA_v1(InputR0)    
End Sub

该功能为我提供了诸如1.2E-305等类似的值。为什么?

0 个答案:

没有答案