与VBA调用C ++成员函数的异步性返回VARIANT

时间:2014-12-18 21:30:32

标签: c++ vba

我在VBA和C ++ DLL之间广泛接口。我通过明确地提供" this"来与VBA函数中的C ++类进行通信。指针作为导出成员函数的第一个参数。这种方法似乎已经适用于不同类型的函数参数和返回。但是我遇到了一个返回VARIANT数据类型的问题。

这是示例DLL代码:

// test.cpp

class C
{
public:
  __declspec(dllexport) void __stdcall f1()
  {
    ...
  }
  __declspec(dllexport) int __stdcall f2()
  {
    return 77;
  }
  __declspec(dllexport) VARIANT __stdcall f3()
  {
    VARIANT v;
    v.vt = VT_I4;
    v.lVal = 77;
    return v;
  }
};

__declspec(dllexport) C *__stdcall get_new_c_ptr()
{
    return new C;
}

这是VBA呼叫代码:

Private Declare PtrSafe Function get_new_c_ptr _
Lib "test.dll" Alias "?get_new_c_ptr@@YGPAVC@@XZ" _
() As LongPtr

Private Declare PtrSafe Sub f1 _
Lib "test.dll" Alias "?f1@C@@QAGXXZ" _
(ByVal c_ptr As LongPtr)

Private Declare PtrSafe Function f2 _
Lib "test.dll" Alias "?f2@C@@QAGHXZ" _
(ByVal c_ptr As LongPtr) As Long

Private Declare PtrSafe Function f3 _
Lib "test.dll" Alias "?f3@C@@QAG?AUtagVARIANT@@XZ" _
(ByVal c_ptr As LongPtr) As Variant

Sub test()
  Dim c_ptr As LongPtr: c_ptr = get_new_c_ptr
    ' c_ptr = &H17D3DB28 is a pointer to a new object of type C
  f1 c_ptr
    ' Correctly calls f1 as the member function of the new object (this == 0x17d3db28)
  Dim i As Long: i = f2(c_ptr)
    ' => Works fine, i = 77
  Dim v As Variant: v = f3(c_ptr)
    ' c_ptr does not get passed correctly and f3 is called with this == 0x0020f288
    ' which is not a valid object of type C. Return is v = Empty
End Sub

0 个答案:

没有答案