gpt4 book ai didi

c# - 如何在 C# 中转换 IDispatch

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:07 25 4
gpt4 key购买 nike

我一直在用 C# 开发 Web 服务,以将网站与本地数据库链接起来。本地应用程序的 SDK 是一个 COM 对象。第二天,我开始思考如何将下面的 VB 代码(在 SDK 协议(protocol)中给出)转换为 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。

最佳答案

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.

你的问题在这里:

 XmlDocument dep_xml = ...
comObject.GetData(dep_xml as IDispatch); // <------ BANG!!

XmlDocument 不是标准的 OLE 自动化/调度类型。它不是:

  • int
  • float
  • 字符
  • BSTR
  • 安全数组
  • etc

...或公开IDispatch 的对象,XmlDocument 未实现的COM 接口(interface)。 XmlDocument 需要 [ComVisible] 存在。

如果对象是 COM 兼容的,那么您可以:

 comObject.SomethingOrOther(myComCompliantObject);

...没有不必要的转换。

关于c# - 如何在 C# 中转换 IDispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com