Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .Net assembly from Win32 without registration?

Tags:

c#

interop

delphi

I'd like to dynamically load and use a .Net assembly created in C# from a Delphi Win32 application. My classes and interfaces are marked as ComVisible, but I would like to avoid registering the assembly. Is this possible?

P.S. I found here link text another good discussion on the topic, but it is more around hosting the CLR. Which begs a question - why would you host CLR versus using ClrCreateManagedInstance?

like image 944
Sergey Aldoukhov Avatar asked Apr 24 '09 19:04

Sergey Aldoukhov


2 Answers

Strangely enough, I couldn't find an answer on StackOverflow, and there is not much on the Net, especially for Delphi. I found the solution from examples posted here. Here's what I got at the end:

function ClrCreateManagedInstance(pTypeName: PWideChar; const riid: TIID;
out ppObject): HRESULT; stdcall; external 'mscoree.dll';

procedure TMyDotNetInterop.InitDotNetAssemblyLibrary;
var
  MyIntf: IMyIntf;
hr: HRESULT;
NetClassName: WideString;
begin
//Partial assembly name works but full assembly name is preffered.
    NetClassName := 'MyCompany.MyDLLName.MyClassThatImplementsIMyIntf,
          MyCompany.MyDLLName';
    hr := ClrCreateManagedInstance(PWideChar(NetClassName), IMyIntf, MyIntf);
    //Check for error. Possible exception is EOleException with ErrorCode
    //FUSION_E_INVALID_NAME = $80131047 2148732999 : The given assembly name 
    //or codebase was invalid.
    //COR_E_TYPELOAD = $80131522 - "Could not find or load a specific type 
    //(class, enum, etc)"
    //E_NOINTERFACE = $80004002 - "Interface not supported".
    OleCheck(hr);
end;

BTW, depending on the situation, you might want to load mscoree.dll dynamically, because it might be not present on the system (XP with no .Net Framework)

EDIT: Unfortunately, this was deprecated and stopped working with .Net4 as I just found out. This leaves only two options - CLR hosting and unmanaged export. Also, debugging of .Net4 COM code is broken.

like image 57
Sergey Aldoukhov Avatar answered Nov 17 '22 19:11

Sergey Aldoukhov


Maybe using RegFreeCOM and a COm-Callable Wrapper.

http://msdn.microsoft.com/en-us/magazine/cc188708.aspx

like image 42
Jonathan Allen Avatar answered Nov 17 '22 19:11

Jonathan Allen