简体   繁体   English

COMException:尝试访问 COM 方法时类型不匹配

[英]COMException: Type mismatch when trying to access a COM method

I tried to access a COM method by using a code like obj.Do("text") while Do is a method in obj which takes a ref string as its input (obj is a .COM object, written in VB6).我试图通过使用像obj.Do("text")这样的代码来访问 COM 方法,而Do是 obj 中的一个方法,它接受一个ref string作为其输入(obj 是一个 .COM 对象,用 VB6 编写)。 However it always throw a COMException type mismatch.但是它总是抛出一个 COMException 类型不匹配。 I tried passing obj.Do(ref a) while a is a string variable but it didn't work either.我尝试传递obj.Do(ref a)而 a 是一个字符串变量,但它也不起作用。

The VB code looks like this VB 代码看起来像这样

Function Generate(sDestinationFile As String)
    ....
Exit Function

Do you know what causes this and how should I work around it?你知道是什么原因造成的,我应该如何解决它?

What does the VB6 cls look like? VB6 cls 是什么样的?

For example, something like this seems to work as a quick test.例如,这样的事情似乎可以作为快速测试。

VB6 cls named stringMe.cls:名为 stringMe.cls 的 VB6 cls:

Dim someString As String

Function AddString(ByRef someString)
    AddString = "Hello " & someString
End Function

I compiled this as an ActiveX DLL.我将其编译为 ActiveX DLL。

In C#, I added a reference to the DLL and coded:在 C# 中,我添加了对 DLL 的引用并进行了编码:

static void Main(string[] args)
{
    StringMe sm = new StringMe();
    object inVar = "world!";
    string returnVar = sm.AddString(ref inVar).ToString();
    System.Console.WriteLine(returnVar);
}

With your VB6 component, make sure you have a Binary Compatibility reference DLL that you put aside so that on each compile it generates the same DispID's for the dll, otherwise the Interop for the .Net project will not be referencing the correct methods.对于您的 VB6 组件,请确保您有一个二进制兼容性参考 DLL,以便在每次编译时为 dll 生成相同的 DispID,否则 .Net 项目的互操作将不会引用正确的方法。

Just remember that when you recompile your VB6 component after you add methods etc, you will need to generate a new Interop for your .Net project.请记住,当您在添加方法等之后重新编译 VB6 组件时,您将需要为您的 .Net 项目生成一个新的互操作。

Use the Commandline parameters into tlbimp to insure that you have a consistent Interop, rather than the default one that it generated when you choose Add Reference to the Com Component.将命令行参数用于 tlbimp 以确保您拥有一致的互操作,而不是选择添加对 Com 组件的引用时生成的默认互操作。

for calling vb6 component from .net you must do like this要从 .net 调用 vb6 组件,您必须这样做

var array = new string[20];
var x = new System.Runtime.InteropServices.VariantWrapper(array as object);
var x2 = x as object;
comComponent.callFunction(ref x2);

this work for me other solution retrun type mismatch error.这对我有用其他解决方案重运行类型不匹配错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM