Here is my other question that led into this one as reference also: How to call managed C++ methods from Un-managed C++
I have successfully created a C# COM File. Now I need a simple explanation on how to implement it in unmanaged C++.
I am following this example but the c++ part is weak. http://www.codeproject.com/Articles/7859/Building-COM-Objects-in-C
Here is my COM file
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cSharpRiJHarn
{
[Guid("ED1483A3-000A-41f5-B1BC-5235F5897872")]
public interface DBCOM_Interface
{
[DispId(1)]
String encrypt(string s);
[DispId(2)]
String decrpyt(string s);
}
[Guid("A6BCEC1D-B60C-4c97-B9AD-1FE72642A9F8"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface DBCOM_Events
{
}
[Guid("7C13A8C6-4230-445f-8C77-0CA5EDECDCB5"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(DBCOM_Events))]
public class RijndaelLink : DBCOM_Interface
{
public String encrypt(String s)
{
return Rijndael.EncryptString(s);
}
public String decrpyt(String s)
{
return Rijndael.DecryptString(s);
}
}
}
I just want a VERY basic example on using this with unmanaged code. Please include in your answers:
- Do I need to include the project or just the source files of the COM
- Do I need to add a reference
- A very basic example of passing a string and printing it out with cout.
Thanks for your help!
The first thing you need to do is properly define the COM object in .NET, to be used by the unmanaged world (C++ or other). Here is a decent definition:
Next, you need to register this .NET assembly for COM using the RegAsm tool. I suggest also you build a Type Library (.TLB) with it, something like this (I suppose you build the whole stuff for X86, not X64):
Please adapt to your actual path. Also check the codebase arg as you may not need this in production.
This will build a .TLB file with both the interface and the class inside. It works because we added the ComVisible attribute. You will also note I have not defined a Dispatch or Dual interface because in this sample, I don't need COM Automation (VB, VBA) nor any scripting language (VBScript, JScript) support, only IUnknown interfaces which are much easier to use in plain C/C++ than IDispatch interfaces.
Now, there is an easy way to import that in the unmanaged c++ world using a Microsoft specific C++ extension: #import Directive, similar to Add References in .NET. Here is a sample Console Application that uses the COM Object:
You will notice the #import directive also create cool wrappers (_bstr_t, as .NET String will be exported as Automation BSTR here, even for IUnknown interfaces) for string handling, so it's no really big deal.
This is not the only way all this can work, but that's IMHO one of the most simple.