Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This example will help you to understand how to implement and use a C# DLL in VB 6.0 code. As C# is an object-oriented language, we can use the object-oriented features to create proper classes in C# DLL. We can use COM Interop or follow the COM Plus Approach to refer to such DLLs in our old VB 6.0 applications. It's like delegating our business logic to this DLL. In this article, I tried to show two different approaches to refer to a C# DLL in VB 6.0. The code is attached herewith; you can directly refer it to understand the following instructions or try to create your own code from the instructions.

To create COM Interop

By using COM Interop, we create a DLL that can be private or shared. This DLL can be referred to in a VB 6.0 application. A VB 6.0 application refers to a Type Library of this DLL, i.e. a file with the .tlb extension that is created using the VS tool utility. For a client of a COM object to have access to the object, the client needs a description of it, how to locate it and how to call its methods and properties. For a "real" unmanaged COM class, this description is available in the form of a Type Library. A Type Library is a binary description of the GUIDs, classes, and interfaces (methods, properties, and parameters) that the COM class supports.

.NET assemblies don't include information in Type Library compatible format. So, it is necessary for the programmer to run one of two .NET-supplied utilities to extract the assembly description of a class into a Type Library file. One utility is tlbexp.exe, the .NET Type Library Exporter. This command-line utility takes as input the name of an assembly DLL file to be converted to a Type Library. The programmer can also specify the name of a Type Library file to be created.

tlbexp ComInteropExample.DLL /out:ComInteropExample.tlb 

Once a Type Library has been created, it can be referenced by a COM client to obtain the information necessary for the COM client to bind to the interfaces of the COM class and activate the COM class at runtime. Another command-line utility for creating a Type Library from an assembly is regasm.exe, the .NET Assembly Registration utility. In addition to creating a Type Library, this utility also creates the Windows Registry entries necessary for making the assembly visible as a COM object to clients, as shown below.

regasm ComInteropExample.DLL /tlb: ComInteropExample.tlb

Note that there is also a property in the Project Properties for a .NET class library DLL called "Register for COM Interop." Setting this property to True instructs the IDE to automatically register the assembly for COM Interop each time you build it, so you don't have to perform this step manually.

Instructions for creating a COM Interop DLL in a Visual Studio 2005 project

  1. Create a new Class Library project in VS 2005, project name: ComInteropExample
  2. Open AssemblyInfo.cs in VS 2005; this is in the Properties folder of the project. Set Com Visible to "True:"
    [assembly: ComVisible(true)] 
  3. Go to Poject Properties -> Build. Check the option Register for Com Interop to "Selected."
  4. Go to class file, e.g. ComInteropClass.cs and add:
    namespace using System.Runtime.InteropServices
    Note that there is no need to add a reference to the InteropServices DLL in Application references.
  5. For interface iInterface,
    define GUID as [Guid("EC87B398-B775-4e6f-BE2C-997D4594CFAA")] 
    [InterfaceType(ComInterfaceType.InterfaceIsDispatch)]
    Note that to create GUID, go to tools -> create GUID -> set GUID format to registry format, copy GUID and add it into your code using the syntax. Write Interface Methods as,
    [DispId(1)] int PerformAddition(int a, int b); 
    [DispId(2)] int PerformDeletion(int a, int b); 
    
    [Guid("EC87B398-B775-4e6f-BE2C-997D4594CFAA")] 
    [InterfaceType(ComInterfaceType.InterfaceIsDispatch)]
     
    public interface iInterface 
    { 
        [DispId(1)] int PerformAddition(int a, int b); 
        [DispId(2)] int PerformDeletion(int a, int b); 
    }
  6. For class ComInteropClass, add statements:
    above class [Guid("5674D47E-6B2A-456e-85C4-CB7AA6AIF24A")] 
    
    [ClassInterface(ClassInterfaceType.None)] 
    [ProgId("ComInteropClass")] 
    
    public class ComInteropClass:iInterface
    
    [Guid("0C216A19-E1B7-4b05-86D3-4C516BDDC041")] 
    [ClassInterface(ClassInterfaceType.None)] 
    [ProgId("ComInteropClass")] 
    
    //this name is used in VB code for late binding Dim the
    
    //Object As Object Set theObject = CreateObject("ComInteropClass")
    
     
    public class ComInteropClass:iInterface 
    { 
        #region iInterface Members public int PerformAddition(int a, int b) 
        { 
            // throw new Exception(
    
                "The method or operation is not implemented."); 
            try 
        { 
            return a + b; 
        } 
    
            catch 
            { 
                return 0; 
            } 
        }
        public int PerformDeletion(int a, int b) 
        { 
            //throw new Exception(
    
                "The method or operation is not implemented."); 
            try 
            { 
                return a - b; 
            } 
            catch 
            { 
                return 0; 
            } 
         } 
         #endregion 
    } 
  7. Register the assembly using the SDK command prompt of VS 2005. Go to the release folder of your project:
    regasm ComInteropExample.DLL /tlb: ComInteropExample.tlb

Refer to this TLB in VB. The VB code is provided with the ZIP file, so please refer to it. It can be used for late binding. If the strong key is not assigned, the assembly will be private, so copy the assembly into the folder where you want to use it. To make the assembly public, assign the strong key to the assembly using the SN tool of VS 2005.

To create COM+

  1. Create a new C# .NET class library project in Visual Studio 2005.
  2. Open the AssemblyInfo.cs file in VS2005. Set following option:
    [assembly: ComVisible(true)] 
  3. Go to the References folder -> right click -> Add references (in .NET tab). Add:
    reference : System.EnterpriseServices
  4. Open a class file (ComPlusClass.cs) and refer Enterprise Service as:
    using System.EnterpriseServices 
  5. Add the following statements below namespaces:
  6. [assembly: ApplicationName("ComPlusExample")] 
    [assembly:Description("ComPlus Assmebly")] 
    [assembly:ApplicationActivation(ActivationOption.Server)] 
    [assembly:ApplicationAccessControl(false)]
  7. Create an interface, e.g. iInterface:
    public interface iInterface 
    { 
        int PerformAddition(int a,int b); 
        int PerformSubtraction(int a,int b); 
    } 
    
  8. Create the class implementing interfaces ServicedComponent and iInterface.
  9. To track events in COM+ for this class, add the following statements:
    [EventTrackingEnabled(true)] 
    [Description("Serviced Component")] 
    [EventTrackingEnabled(true)] 
    [Description("Interface Serviced Component")]
    
        Collapse [EventTrackingEnabled(true)] 
                 [Description("Serviced Component")] 
                 [EventTrackingEnabled(true)] 
                 [Description("Interface Serviced Component")] 
    
    public class ComPlusClass:ServicedComponent,iInterface 
    {
        #region iInterface Members
    
        public int PerformAddition(int a, int b) 
        { 
             // throw new Exception(
    
                 "The method or operation is not implemented."); 
             try 
             { 
                 return a + b; 
             } 
                 catch 
             { 
                 return 0; 
             } 
        }
    
        public int PerformSubtraction(int a, int b) 
        { 
            //throw new Exception(
    
                "The method or operation is not implemented."); 
            try 
            { 
                return a - b; 
            } 
                catch 
            { 
                return 0; 
            }
            #endregion 
        }
    }
  10. Build the Application. Assign the strong key to the Application using the VS 2005 command prompt. Go to Start-> Program files-> Visual Studio 2005-> Visual Studio tools -> SDK command prompt.
    sn -k ComPlusClass.snk 
    Add this strong key to Application properties -> Signing -> Strong key
  11. To register the assembly:
  12. To view this registered COM+ go to Control Panel -> Administrative Tools -> Compoent Services. In Component Services -> Computers -> My Computer -> Com + Applications. Here, right click on it. You can create MSI for it.

Summary

Refer to the TLB of the assembly from the Release folder to use in VB6 applications. Please let me know if you have any problems; my email is gunijan_rakesh@yahoo.co.in. I have tried to make this article a readable one and I will try to improve it with your invaluable suggestions. Thank you.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
General[Message Deleted]
BabakAghili123321
6:08 8 Dec '09  

GeneralRe: making a TOOL to automate this process for us
RakeshGunijan
7:07 8 Dec '09  
Hi Babak,
Are you trying to convert old Vb source code to c#?
This article explains about accessing C# assmbly in VB.
Could you explain in detail what exactly you want to achieve?
I am sorry as I dont understand VB stuffs.

Regards.
General[Message Deleted]
BabakAghili123321
7:20 8 Dec '09  

GeneralRe: making a TOOL to automate this process for us
RakeshGunijan
7:53 8 Dec '09  
You are not required to use GUID as well as well as strong keys for ComInterOp Approach (I hope 'first method' means ComInterop only)

I am assuming that you want to automate following kind code stuff like one in above article:

theObj = CreateObject("ComInterOpClass")
Text6.Text = theObj.PerformAddition(Text4.Text, Text5.Text)

If yes, then you have to use CLASSNAME defined in [ProgId("CLASSNAME")] atrribute of C# class in vb source code.

Sounds intresting what you want to achive Smile
Generalautomation error the system cannot find the file specified urent
gnsrinu1@gmail.com
8:54 25 Jul '09  
I used this concept in my application. It is working fine on my development system.
After that i try to run my application on some other machine Where vb 6.0 and .NET 2.0 framework is installed. The application showing the following error "automation error the system cannot find the file specified".

i registered the dll on the testing machine by using regasm.

I placed the dll and tlb files in same path as develpment machine.

dim obj as Operation.addition
set obj = new operation.addition -------------> here it is showing the errir "automation error the system cannot find the file specified"
dim str as string
msgbox(obj.add(10,20))

It is very urgent to me.
Can anbody help me out from ths situation.
GeneralRe: automation error the system cannot find the file specified urent
RakeshGunijan
21:13 25 Jul '09  
Hi,
I am assuming that u r using Com plus approach.
dim obj as Operation.addition
Is addition an interface?

ur code shld be somthing like this:
Dim theObj As ComPlusExample.iInterface
Set theObj = New ComPlusClass
where theObj is declared of type interface and initialised as concrete class.
GeneralRe: automation error the system cannot find the file specified urent
gnsrinu1@gmail.com
21:23 25 Jul '09  
Hi Gunjan,

Thanks for you quick response.

Now i am in office only.

But i am using com interop.
Could you please provide me the solution.

Thanks & regards]
Srinivas.
GeneralRe: automation error the system cannot find the file specified urent
gnsrinu1@gmail.com
23:37 26 Jul '09  
Dear Rakesh,

Thanks for your support.

I got the solution. Now it is working fine on my testing machine.

The following is the command i executed.

c:/> WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyDotNetComDLL.dll /tlb:MyDotNetComDLL.tlb /codebase

It registred the dll successfully, but it shown some warning.

Thanks & regards
Srinivas
Generalautomation error the system cannot find the file specified
gnsrinu1@gmail.com
8:51 25 Jul '09  
I used this concept in my application. It is working fine on my development system.
After that i try to run my application on some other machine Where vb 6.0 and .NET 2.0 framework is installed. The application showing the following error "automation error the system cannot find the file specified".

i registered the dll on the testing machine by using regasm.

I placed the dll and tlb files in same path as develpment machine.

dim obj as Operation.addition
set obj = new operation.addition -------------> here it is showing the errir "automation error the system cannot find the file specified"
dim str as string
msgbox(obj.add(10,20))

It is very urgent to me.
Can anbody help me out from ths situation.
QuestionRe: I need help with passing arrays as parameters
mla154
10:18 23 Apr '09  
I created a C# DLL COM Interop with the help of this article:
C# Com[^]

I have also successfully loaded the TLB file into Visual Basic.
However, if in C# I make one of the parameters a double array like so:

//This is C#
[System.Runtime.InteropServices.DispId(4)]
void Test(ref double[] b);

..and in Visual Basic 6 try to call it

'This is VB
Dim d() As Double
Dim c As New csClass
c.Test d

...I find that the VB6 code crashes on the call to Test.  I get a message:
Visual Basic has encountered a problem and needs to close.  We are sorry for the inconvenience. If you were in the middle of something, the information you were working on might be lost.

Does anyone have any ideas of what the problem may be?

Regards,
Mike

AnswerRe: I need help with passing arrays as parameters
Member 4320844
22:42 14 Jul '09  
Hi
I have the following notes for you to check it out in your code:

1- First .. Have you Compiled your C# Code to be Sure 100 Percent that
Your C# Code Contains no Bugs Or Not .
2- Second : In your VB Code :

Dim d() As Double
Dim c As New csClass
Rem Since you have Created a Dynamic array , You need to use :
Rem ReDim d(5) As ... for 5 elements say , Or to use:
Rem Redim preserve d(7) As ... for expanding (resize) the array with out wiping the old
content.
Rem So you must have the following statement at least :
ReDim d(8) : rem if you need 8
Rem Then use :
c.Test d(1)

Rem Or you must have a Loop I= 1 to 8 : C.Test d(I) : Next I

3- Third: for the declaration of the Class Instance
Rem I dont see Set c= New csClass after your Dim c as New csClass

Rem since Declaring of a class instance in one of the two available declarative ways.
Rem may not work in your environment , so use the other way of declaring.
4- Forth: you may need to declaire an array of the class instance instead of declaring d() as an
array,if this is true you must apply dynamic array declaration and ReDim .... statement for your class declaration and this depends on your entire code which is not visible to us to guess your problem more precisely.
I hope this leads you to find out what is Incomplete in your code ... check please.
QuestionStuck ! The System Cannot Find the file specified.
wupaz
11:14 26 Feb '09  
I do all stuff...

I have this code (vb6) and on bold line I have the damn "The System Cannot Find the file specified."

Private Sub Form_Load()

Dim sd As ComInterOpExample.ComInterOpClass
sd = New ComInterOpExample.ComInterOpClass Dim d As String
d = sd.PerformAddition(1, 2)

End Sub


Anyone could help me ?
AnswerRe: Stuck ! The System Cannot Find the file specified.
Member 4320844
23:00 14 Jul '09  
Hi

1- When You Declare a Class Like :
Dim sd As ComInterOpExample.ComInterOpClass

As you did in your Form Load.
2- Yo need to Use Set .......the varible As follows :

Set sd = New ComInterOpExample.ComInterOpClass

3- Check d Type to match with sd.PerformAddition(1, 2) value Type returned, otherwise
you will get Type mismatch error.

I noticed , you forgot Set in your Statement Code written in Bold.
Hope it works.
QuestionRe: Great article - Could someone help me with the next step?
mla154
11:30 24 Feb '09  
Hello,
I greatly appreciate this article.  Because of the To create COM Interop section, I was able to create a TLB file and use VB6 to import it.
I would very much like to know how to import a TLB into a Visual C++ 6.0 program.  Can anyone demonstrate this to me or show me another article/link in which I can find what I'm looking for?  Any help at all is appreciated.

Regards,
Mike

AnswerRe: Great article - Could someone help me with the next step?
mla154
12:08 24 Feb '09  
I figured it out. Smile

Regards,
Mike

AnswerRe: Great article - Could someone help me with the next step?
yangbing1008
16:00 11 Apr '09  
Could you let me know how to import TLB into c++ or show me an example? Thanks.

Michael
AnswerRe: Great article - Could someone help me with the next step?
mla154
5:04 13 Apr '09  
Hello Michael,
1. Open the class wizard (Ctrl-W).
2. Choose Add Class 3. Choose From a type library... 4. Choose TLB file to open.
etc.

Regards,
Mike

GeneralRe: spelling error in article
mla154
10:16 23 Feb '09  
Hello,
Under your To create COM Interop section, please change all references of
[InterfaceType(ComInterfaceType.InterfaceIsDispatch] to

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch]

This corrects compiler errors.  I assume this is what you meant to do.

Regards,
Mike

GeneralRe: spelling error in article
ADumbProgrammer
1:42 24 Feb '09  
Hello Mike,
Sorry for the typo mistake.

I am working on having a updated version of Document. Will make sure removing such mistakes.

Again thanks for your suggestions.
GeneralExample works for VS 2008 also
GKindel
12:02 11 Jan '09  
Thanks for a great example of a standard cominterop project. I have able to add a VB6 com complaint to a .net 3.5 framework DLL containing a public interface and a class using the interface.
Thanks again Gary K.
GeneralGreat Article - Heres some tips I found
bugnuker
14:12 13 Nov '08  
Hey, thanks for this. This was really helpful for me.
I had a project where I needed to use .NET 2.0 to use a web service.
I needed to be able to make a dll that vb6 could call and use.

I had some troubles, and I thought I would share them here so others may have an easier time.
I found that the comPlus never worked for me. I found that the comPlus also was making my project not build an EXE
I removed the comPlus from the VB6 application.
I added the reference after the regasm.
I had some problems with a MISSING: prefix but it does not seem to affect the project.
I found that the VB6 project would never debug. It would always say file not found.
If you build the .EXE and place it in the folder with the .tbl and .dll, it works FLAWLESSLY


this is just my account of how things went for me. Others might have had no problems.
thanks again!
Questionhow to fire events on VB6? [modified]
Calenturator
11:33 1 Dec '07  
What could be done if we have an event in C# (a simple button for example) and we would like to fire also an event in VB6 ?

(if we push the button in C#, that certain fucntion will be fired in VB6 app).

Could this be possible? Dead

Enrique.

kikeman.


-- modified at 1:11 Sunday 2nd December, 2007
QuestionWhat would be better - COM Interop or COM++?
Calenturator
9:51 1 Dec '07  
Great article, I was looking for a general overview of how to use C# from the old VB6. Smile

In you opinion my friend what would be better of these two aproaches: COM Interop or COM++? Confused

Concidering that those C# Class libraries would be called also from other C# WinApps.

Thanks a lot in advance.
Enrique.

kikeman
GeneralThe format of the file 'myDll' is invalid.
johnsonch
1:20 31 Aug '07  
When I use dll in excel it's show the error message
'The format of the file 'myDll' is invalid.' i 've check
i have copy mydll.dll file to excel folder but it's always show
that message and can't works!!
Do you know why?


johnson
GeneralRe: The format of the file 'myDll' is invalid.
gunijan_rakesh
4:15 31 Aug '07  
Can u please provide some details as:
where are you using it?
Some background or context?Confused


Last Updated 25 May 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010