2010-06-08 73 views
9

我使用c#编写了一个.NET程序集,以执行将由托管和非托管代码使用的函数。我有一个VB6项目,现在需要通过COM使用程序集。在VB6中引用.NET程序集将不起作用

我创建了我的.net程序集,确保ComVisible设置为true,并且它已通过项目属性注册为COM interop。

public class MyClass 

    [ComVisible(true)] 
    public string GetResponse() 
    { 
     return "Testing Response" 
    } 

} 

我生成程序集并将文件复制到一个文件夹中。 TestInterop.dll

然后我运行一个批处理文件来注册组装工具来注册对象的COM。

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ 
regasm "c:\Program Files\TestApp\TestInterop.dll" /tlb:TestInterop.tlb 

我打开一个新的VB6应用程序和参考TestInterop.dll

在VB6我写了下面的代码并将其编译。

Dim obj as TestInterop.MyClass 
Set obj = new TestInterop.MyClass 

Dim strTest as string 

strTest = obj.GetRespose() 

当我运行程序时,它在obj.GetResponse()行发生错误。

Run-time error' -2147024894 (80070002'): 
Automation error 
The system cannot find the file specified 

此外,intellesense不能在obj上工作。我必须输入GetResponse方法。这是正常的吗?

有没有人有任何线索可能是错误的或我错过了什么步骤。谢谢!

回答

11

你会想把你的.NET程序集放到GAC中,或者使用/ codebase命令行开关运行RegAsm(它会报错,但这至少会起作用)。不幸的是,没有智能感知是正常的。

+0

工作就像一个魅力。非常感谢!我使用/ codebase命令运行regasm工具。/codebase也为你创建了tlb文件。感谢大家的回应。 – dretzlaff17 2010-06-08 19:25:24

4

上次我看到我忘记了硬编码的GUID。所以每次我重新编译VB都无法找到我的代码。这是来自VB.NET的模板。 (不要使用这些GUID,使你自己的)

<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _ 
Public Class ComClass1 

#Region "COM GUIDs" 
    ' These GUIDs provide the COM identity for this class 
    ' and its COM interfaces. If you change them, existing 
    ' clients will no longer be able to access the class. 
    Public Const ClassId As String = "eaf83044-f0a7-417b-b333-e45aec398ca5" 
    Public Const InterfaceId As String = "84e0fb8f-266d-40e6-9e8c-3d4eb37d3bf0" 
    Public Const EventsId As String = "22ea2214-032f-4eb6-b2d4-c5dd213bab87" 
#End Region 

    ' A creatable COM class must have a Public Sub New() 
    ' with no parameters, otherwise, the class will not be 
    ' registered in the COM registry and cannot be created 
    ' via CreateObject. 
    Public Sub New() 
     MyBase.New() 
    End Sub 

End Class 
0

我想,是框架目录下生成的TLB文件针对这个目录(C:\ Program Files文件\ TestApp)。

难道这就是问题吗?

1

我注意到,你不需要手动运行RegAsm,实际上只是设定集信息属性标记有ComVisible特性设置为true:

[组件:标记有ComVisible特性(真)]

您还可以通过这样做去项目属性 - >应用程序 - >程序集信息 - >使程序集COM可见,并设置复选框。

无需将您创建的程序集注册到GAC中,以便在VB6中使用它。

0

直到我直接从exe运行vb6消费者代码之前,我的错误或其他错误无论我尝试了什么,都出现了-2147024894错误或其他错误。关于VB6调试器的一些问题阻止了我在运行时使用该DLL。我甚至无法实例化对象。我可以在设计时参考tlb,并且也有完美的智能感知支持。只要我在Visual Studio之外启动应用程序,一切都很完美。希望这可以帮助某人。