问题描述
我有两个通过 COM 互操作公开的 .NET 类 - 比如说 Foo 和 Bar,我需要将 Foo 类型的参数传递给 Bar 中定义的方法.像这样的:
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)
我得到一个错误:
D: est.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.
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 设置为 None,因此不会显示任何内部结构.这样你的类型库会更干净.
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 互操作中传递强类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!