Tuesday, January 17, 2006

exposing a .NET assembly to be used as a COM object (from any language like Delphi, VB, etc)

this is really simple but many programmers don't know just how simple it is, the steps are:


- create a class library
- add using System.Runtime.InteropServices;
- add these attributes to the class you want to expose
[ComVisible(true),
Guid("YOUR GUID HERE"),
ClassInterface(ClassInterfaceType.AutoDispatch)]
- each method that you want to expose needs to have the [ComVisible(true)] attribute specified
- the methods you expose CANNOT be static

that's it!

here's a complete class library that provides a method to encrypt a string:

using System;
using System.Security.Cryptography;
using System.Text;
using System.Runtime.InteropServices;
//[assembly: System.Runtime.InteropServices.ComVisible(true)]
namespace LoginHash
{
///
/// Provides a method to hash strings using MD5
///

///
[ComVisible(true),
Guid("A8E2505C-8A1B-49F9-AFD1-54B79B26040C"),
ClassInterface(ClassInterfaceType.AutoDispatch)]
public class Login
{
[ComVisible(true)]
public string Encrypt(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes( cleanString );
Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
return BitConverter.ToString(hashedBytes);
}
public Login()
{
}
}
}


so you see, it's really easy to export all the functionality that you have in .NET to other applications / languages using COM. Next I'll post examples on how to use this COM object

No comments: