![](/img/trans.png)
[英]How can I pass VBA variant array data type through COM interop into C# method
[英]How to pass variant* to C# through InvokeHelper?
我有一個遺留的 c++ 組件。它使用類似性質的 ATL 控件。程序 ID 是該組件的輸入。 它使用 progid 創建 ATL 對象,並使用 dispatchid 使用 InvokeHelper 從 ATL 控件調用方法,如下所示,
DISPID methodDispID; // dispatchid
long lValue = 0; // first argument long
short nIdx = 1 // second argument short
VARIANT varValue; // third argument variant
long returnCode = 0; // return code long
static BYTE parms[] = VTS_I4 VTS_I2 VTS_PVARIANT;
InvokeHelper(methodDispID, DISPATCH_METHOD, VT_ERROR, (void*)&returnCode, parms, &varValue, lValue, nIdx);
在 C++ ActiveX 方法中,如下所示,
[id(1), helpstring("method GetValue")] long GetValue(long lValue, short nIdx,VARIANT *varValue);
現在我試圖在 C# 中引入 Active X,這意味着我有一個用戶控件,我將這個 C# 用戶控件的 progid 提供給遺留組件,它創建 C# 用戶控件的對象並嘗試調用 C# 用戶控件的 GeValue 方法,定義如下,
C#
interface IMyInterface
{
[DispId(1)] Int32 GetValue(System.Int32 lOrder, System.Int16
nIdx,object varval);
}
class MyClass : IMyInterface
{
System.Int32 GetValue(System.Int32 lValue, System.Int16 nIdx,
ref object vCBValue)
{
}
}
調用是對 C# 用戶控件的 GetValue 方法的調用,但它拋出了異常
System.Runtime.InteropServices.COMException at System.RuntimeType.ForwardCallToInvokeMember(System.String, System.Reflection.BindingFlags, System.Object, Int32[], System.Runtime.Remoting.Proxies.MessageData ByRef)
我嘗試如下更改 C# 方法定義,但沒有任何效果,
System.Int32 GetValue(System.Int32 lValue, System.Int16 nIdx,
[MarshalAs(UnmanagedType.Struct)] ref object varValue);
System.Int32 GetValue(System.Int32 lValue, System.Int16 nIdx,
ref IntPtr varValue);
如何通過 InvokeHelper 將變體* 傳遞給 C#?
注意:對於 C++ 和 C# 用戶控件,使用 InvokeHelper 調用方法的組件代碼應該相同
如果您嘗試重現 C++ COM 代碼:
[id(1), helpstring("method GetValue")]
long GetValue(long lValue, short nIdx,VARIANT *varValue);
...到c#,然后代替
System.Int32 GetValue(System.Int32 lValue, System.Int16 nIdx, ref object vCBValue);
...它應該是:
object GetValue(System.Int32 lValue, System.Int16 nIdx);
那是因為所有 c++ COM 方法都返回 HRESULT(在您的情況下為 long),任何其他返回值都通過out
參數。
在 .NET 中,不需要定義 HRESULT,我們可以顯式返回值而不是使用out
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.