【问题标题】:how to put IDispatch* in managed code如何将 IDispatch* 放入托管代码中
【发布时间】:2014-01-31 14:36:19
【问题描述】:

我一直在考虑尝试使用 C# 编写一个实现 OPOS 服务对象的 COM 对象。我已经使用自动化和 MFC 在 C++ 中完成了它,这并不太难。因此,我坚持尝试将其转换为一种方法。我将排除界面中的其他方法,因为它们是直截了当的(或者我希望如此)。

[id(6), helpstring("method OpenService")]
LONG OpenService(BSTR lpclDevClass, BSTR lpclDevName, IDispatch* lpDispatch);

到目前为止,我的 C# 代码看起来像这样,但我被困在 OpenService 上。

[ComVisible(true)]
[Guid("76F8309C-3837-4065-960F-BE156383896D")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class IErtMSR
{
    [DispId(1)]
    int COFreezeEvents([MarshalAs(UnmanagedType.VariantBool)] bool Freeze);
    [DispId(2)]
    int GetPropertyNumber([In] int lPropIndex);
    [DispId(3)]
    void SetPropertyNumber([In] int lPropIndex, [In] int nNewValue);
    [DispId(4), MarshalAs(UnmanagedType.BStr)]
    string GetPropertyString([In] int lPropIndex);
    [DispId(5)]
    void SetPropertyString([In, MarshalAs(UnmanagedType.BStr)] string StringData);
    [DispId(6)]
    int OpenService([In, MarshalAs(UnmanagedType.BStr)] string lpclDevClass, [In, MarshalAs(UnmanagedType.BStr)] string lpclDevName, IDispatch* lpDispatch);
    //...the rest of the 24 methods.
}

如您所见,我不知道要为 IDispatch* 放什么。在这种情况下我应该使用什么?

【问题讨论】:

  • 我想通了。我必须创建一个 IDispatch 方法(我发现 Hans Persant 有这个方法可用..)现在我只需要弄清楚如何从中调用一个事件.. :)

标签: c# automation com-interop


【解决方案1】:

您无需为 COM IDispatch 创建托管定义或显式实现其成员。该框架具有对它的内置支持。只需像这样声明您的OpenService

[DispId(6)]
int OpenService(
    [In, MarshalAs(UnmanagedType.BStr)] string lpclDevClass, 
    [In, MarshalAs(UnmanagedType.BStr)] string lpclDevName, 
    [In, MarshalAs(UnmanagedType.IDispatch] object lpDispatch);

【讨论】:

  • 在我的脑海中,我认为这工作得很好,但签名显示 IDispatch*。我不应该做到ref object lpDispatch吗?
  • @RobertSnyder, no, ref object 意味着可以从调用中返回 IDispatch 对象。这将映射到 IDL 中的 [in, out] IDispatch** p。只需确保您传递的object 实现了IDispatch 兼容接口,例如:[InterfaceType(ComInterfaceType.InterfaceIsDual] interface ITest { /*... */ }。您也可以在对象的class 上使用[ClassInterface(ClassInterfaceType.AutoDispatch/AutoDual)],但我会坚持使用单独的接口,例如类上的ITest[ComDefaultInterface(typeof(ITest))]
猜你喜欢
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 2012-03-04
  • 2010-09-18
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多