How Do I...Pass Simple Data from .NET Code to VB6 code?
This example demonstrates how to use .NET objects from a Visual Basic 6.0 application. The same
technique can be used to create the object from any COM application, including those built
with Visual C++ 6.0, VBScript, or JScript.
In this example, a very simple class called Test implements the ITest interface. This interface
has a single method that returns the current time and can be easily used from COM. It is possible to
avoid an explicit definition of interface and use class interface, which contains all of the members of
the class and all the members of its base classes. This technique is available by applying the
DefaultInterface.AutoDual attribute but is strongly discouraged because it seriously limits
your ability to version your classes.
namespace TestServer{
public interface ITest{
DateTime GetTime();
}
public class Test : ITest{
DateTime ITest.GetTime(){
return DateTime.Now;
}
}
}
C#
After compiling the managed code to create the TestServer assembly, the assembly must be installed in the
global assembly cache (GAC) and registered for use from COM. Use gacutil.exe to install the TestServer
assembly in the GAC and add the registry entries needed to make the types within the assembly creatable
from COM.
gacutil /i TestServer.dll
In order to use the types defined within the TestServer assembly from Visual Basic 6.0, it helps to
have a type library that describes the types contained in the assembly. Use tlbexp.exe to produce
a type library from any managed assembly or check the option in the Build Project settings to "Register for COM Interop".
The type library produced by tlbexp.exe can then be added to the project through the Project/Reference dialog
in Visual Basic 6.0. Once the reference to the type library is added to the project, the types defined
in the assembly can be referenced directly within the Visual Basic code.
Dim dotNETServer As TestServer.ITest
Set dotNETServer = New TestServer.Test
Debug.Print ".NET server returned: " + FormatDateTime(dotNETServer.GetTime, vbGeneralDate)
In order to run the application, the assembly is typically installed in
the global assembly cache as described above. During development, it is easier to simply copy the assembly to the application directory. Assemblies
can only be located if they reside in the application directory or in the
global assembly cache.
Note: If you are trying to run the application from within
the Visual Basic 6.0 development environment, the assembly must be in the same
directory as vb6.exe because vb6.exe is the process hosting the assembly.
VB Test Client
[This sample can be found at e:\web\quickstart\QuickStart\howto\samples\Interop\TestServer_1\]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.
|