重写Word AddIn:无需注册源程序集,将COM对象转接口
Word AddIn COM互操作强类型转换问题
我正在重写一个Word AddIn,核心结构如下:
MyAddIn提供SetController方法,用于传递控制器实例,实现C#主程序与C#插件的通信MyAddIn.dll已注册为COM互操作,通过Office的RequestComAddInAutomationService机制返回COM对象,允许主程序调用SetController方法
插件端COM交互代码
using MyWordAddIn; using System.Runtime.InteropServices; namespace MyWordAddIn; [ComVisible(true)] [Guid(IAddInUtilities_GUID)] public interface IAddInUtilities { void SetController(object obj); } [ComVisible(true)] [Guid(AddInUtilities_GUID)] [ClassInterface(ClassInterfaceType.None)] [ComSourceInterfaces(typeof(IAddInUtilities))] public class AddInUtilities : StandardOleMarshalObject, IAddInUtilities { public void SetController(object obj) { Globals.ThisAddIn.Controller = obj; } }
客户端主程序调用代码
获取AddInUtilities的COM实例后,调用方式如下:
var comInstance = ...; var addInUtilities = (MyWordAddIn.IAddInUtilities)comInstance; var ctrl = new Controller(); ctrl.Text = "test"; addInUtilities.SetController(ctrl);
Controller类定义
[ComVisible(true)] [Guid(Controller_GUID)] [ClassInterface(ClassInterfaceType.AutoDual)] public class Controller { public string Text { get; set; } }
当前问题
在插件中,ThisAddIn.Controller被设置为COM对象实例,目前只能通过转换为dynamic来读取Text属性:
string txt = ((dynamic)this.Controller).Text;
我希望能将其转换为强类型的类或接口,但无论如何定义接口,都会抛出InvalidCastException。我知道注册主程序集可以解决,但希望避免这个操作。最坏情况可以用dynamic包装类,但非常不想这么做。
内容的提问来源于stack exchange,提问作者Timur Kelman
相关产品推荐
相关产品推荐

