在 .NET COM 互操作中传递强类型参数

0

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

问题描述

我有两个通过 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 互操作中传递强类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14