我一直在開發Web服務在C#鏈接網站與本地數據庫。本地應用程序的SDK是一個COM對象。我打破我的心就如何轉換下面的VB代碼的第二日(在SDK協議給予),以C#相當於:如何投射IDispatch在C#
XML_DOM := CreateOleObject('MSXML2.DOMDocument.3.0') as IXMLDOMDocumen
GetData(XML_DOM as Idispatch)
我已經試過這樣:
System.Type objType = System.Type.GetTypeFromProgID("PERCo_S20_SDK.ExchangeMain");
dynamic comObject = System.Activator.CreateInstance(objType);
if (comObject.SetConnect("192.168.1.14", "211", "ADMIN", "") != 0)
{
//Could not connect to server!
}
XmlDocument dep_xml = new XmlDocument();
XmlDeclaration dep_xml_decl = dep_xml.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlElement root = dep_xml.DocumentElement;
dep_xml.InsertBefore(dep_xml_decl, root);
XmlElement element = dep_xml.CreateElement(string.Empty, "documentrequest", string.Empty);
element.SetAttribute("type", "subdiv");
dep_xml.AppendChild(element);
comObject.GetData(dep_xml as IDispatch);
comObject.Disconnect();
與
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")]
private interface IDispatch
{
[PreserveSig]
int GetTypeInfoCount(out int Count);
[PreserveSig]
int GetTypeInfo
(
[MarshalAs(UnmanagedType.U4)] int iTInfo,
[MarshalAs(UnmanagedType.U4)] int lcid,
out System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo
);
[PreserveSig]
int GetIDsOfNames
(
ref Guid riid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)]
string[] rgsNames,
int cNames,
int lcid,
[MarshalAs(UnmanagedType.LPArray)] int[] rgDispId
);
[PreserveSig]
int Invoke
(
int dispIdMember,
ref Guid riid,
uint lcid,
ushort wFlags,
ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams,
out object pVarResult,
ref System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo,
out UInt32 pArgErr
);
}
,但我得到的錯誤
An exception of type 'System.ArgumentException' occurred in System.Dynamic.dll but was not handled in user code
Additional information: Could not convert argument 0 for call to GetData.
請幫我解決一下如何在C#中投射IDispatch。
很明顯,您正在使用.NET XmlDocument類,而不是它的非託管味道(MSXML2.DOMDocument.3.0)。它不能轉換爲IDispatch。項目>添加參考> COM選項卡,選擇「Microsoft XML,v3.0」 –
@HansPassant添加對「Microsoft XML,v3.0」的引用。什麼應該是傳遞參數部分:GetData(XML_DOM作爲Idispatch)? –
使用'new MSXML2.DOMDocument30()'創建對象,不需要強制轉換。 –