传递强类型的参数在.NET中COM互操作 [英] Passing strongly typed arguments in .NET COM interop

查看:191
本文介绍了传递强类型的参数在.NET中COM互操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过COM互操作暴露2 .NET类 - 假设Foo和酒吧,我需要Foo类型的参数传递给在酒吧定义的方法。事情是这样的:

I have two .NET classes exposed via COM interop - let's say Foo and Bar, and I need to pass an argument of type Foo to a method defined in Bar. Something like this:

[ComVisible(true)]
public class Foo
{
    // whatever
}

[ComVisible(true)]
public class Bar
{
    public void Method(Foo fff)
    {
        // do something with fff
    }
}

当我运行下面的VBS(使用的Cscript.exe):

When I run the following VBS (using cscript.exe):

set foo = CreateObject("TestCSProject.Foo")
set bar = CreateObject("TestCSProject.Bar")
call bar.Method(foo)

我得到一个错误:

I get an error:

D:\ test.vbs(3,1)Microsoft VBScript运行时错误:无效的过程调用或参数:'bar.Method

不过,如果我改变了方法声明如下:

However, if I change the Method declaration to this:

    public void Method(object o)
    {
        Foo fff = (Foo)o;
        // do something with fff
    }

一切正常。我尝试了一些魔术接口,属性等,但至今没有运气。

everything works. I tried some magic with interfaces, attributes, etc. but no luck so far.

任何见解?

感谢

推荐答案

请确保你定义一个GUID属性,这是必要的,如果你犯了一个的QueryInterface(VB做可能)。你必须生成一个新的唯一的GUID为每个标记有ComVisible特性类

Make sure, you define a GUID attribute, this is necessary if you make a QueryInterface (VB does probably). You have to generate a new unique GUID for every comvisible class.

[Guid("77777777-3333-40df-9C0D-2B580E7E1F3B")]
[ComVisible(true)]
public class Foo
{
}

然后,我会强烈建议编写接口的COM对象,并设置ClassInterface为无,所以没有内部显露。您的类型库将是更清洁的这个样子。

Then i would strongly recommend to write interfaces for your COM objects, and set the ClassInterface to None, so no internals are revealed. Your typelibrary will be much cleaner this way.

[Guid("88888888-ABCD-458c-AB4C-B14AF7283A6B")]
[ComVisible(true)]
public interface IFoo
{
}

[ClassInterface(ClassInterfaceType.None)]
[Guid("77777777-3333-40df-9C0D-2B580E7E1F3B")]
[ComVisible(true)]
public class Foo : IFoo
{
}

这篇关于传递强类型的参数在.NET中COM互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆