I have a C# dll that I need to call from unmanaged C++. The main problem that I have is that my c++ code corresponds to an excel add-in, that can be installed for excel 2003 and excel 2007, when I install my add-in in excel 2007, and I try to call my C# dll, it works just fine, but for some reason that I still haven’t been able to find, in excel 2003 it crashes, excel show me a Runtime Error message, and when debugging my c++ code I can see that the code fails when trying to create an instance of my C# dll, it says that the class is not registered even if I registered with regasm.
this is my C# code:
namespace ManagedDLL
{
[
Guid("3C80EE60-D9B8-4daf-89BE-6C7B748F613C"),
InterfaceType( ComInterfaceType.InterfaceIsDual),
ComVisible(true)
]
public interface ICalculator
{
[DispId(1)]
int main(string args, IntPtr _handle);
};
[
Guid("5134F342-5B7F-4db2-94F0-F450610419CF"),
ProgId("myapp.CCOMEntryPoint"),
ClassInterface(ClassInterfaceType.None),
ComDefaultInterface(typeof(ICalculator)),
ComVisible(true)
]
public class COMEntryPoint : ICalculator
{
public int main(string args, IntPtr _handle)
{
string[] _args = args.Split(new char[] { ':' });
Program.handle = _handle;
return Program.Main(_args);
}
}
}
and in C++ what I do is to import the .tlb file that is generated when I use regasm to register my C# dll, like this:
\#import "..\bin\release\ManagedDLL.tlb" raw_interfaces_only
using namespace ManagedDLL;
.
.
.
int callMyDll()
{
long handle = 0, result = 0;
BSTR args;
HRESULT hr = CoInitialize(NULL);
ICalculatorPtr pICalc(__uuidof(COMEntryPoint));
pICalc->main(bstrStr, handle, &result);
return result;
}
But as I mentioned before, this code doesn’t work for excel 2003, so my questions are:
- I’m I doing something wrong in the way in which I declare my C# dll that is causing me problems in excel 2003?
- Just as it is now, can my C# dll be considered an ActiveX object?
- How can I call my C# dll in another way from c++? like using IDIspatch for example
Thanks
I’ve had a similar problem before. I wasn’t calling C# from C++, but the concept is the same.
I had to load a .NET dll into a host application via COM, which looks like what you are trying to do. The problem was the host application (in your case excel) was loading the .NET runtime 1.1. Our dll was compiled for .NET 2.0.
It could be that Excel 2003 is loading the 1.1 runtime and 2007 loads a more recent version. Check out this forum this:
Excel selects wrong .NET runtime.
You could also test this by using MSBee to target the 1.1 runtime and then try load your dll in Excel 2003.