title: Hosting CLR in Delphi with/without JCL - example
body: <p>Can somebody please post here an example how to host CLR in Delphi? I have read similar <a href="https://stackoverflow.com/questions/258875/hosting-the-net-runtime-in-a-delphi-program">question</a> here but I cannot use JCL as I want to host it in Delphi 5. Thank you.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> This <a href="http://www.west-wind.com/Weblog/posts/104449.aspx" rel="nofollow noreferrer">article</a> about hosting CLR in Fox Pro looks promising but I don't know how to access clrhost.dll from Delphi.</p>
  
  <hr>
  
  <p><strong>Edit 2:</strong> I give up on Delphi 5 requirement. Now I'm trying JCL with Delphi 7. But again I am unable to find any example. Here is what I have till now:</p>
  
  <p>My C# assembly:</p>
  
  <pre><code>namespace DelphiNET
  {
      public class NETAdder
      {
          public int Add3(int left)
          {
              return left + 3;
          }
      }
  }
  </code></pre>
  
  <p>I have compiled it to <code>DelphiNET.dll</code>.</p>
  
  <p>Now I want to use this assembly from Delphi:</p>
  
  <pre><code>uses JclDotNet, mscorlib_TLB;
  
  procedure TForm1.Button1Click(Sender: TObject);
  var
    clr: TJclClrHost;
    ads: TJclClrAppDomainSetup;
    ad: TJclClrAppDomain;
    ass: TJclClrAssembly;
    obj: _ObjectHandle;
    ov: OleVariant;
  begin
    clr := TJclClrHost.Create();
    clr.Start;
    ads := clr.CreateDomainSetup;
    ads.ApplicationBase := 'C:\Delhi.NET';
    ads.ConfigurationFile := 'C:\Delhi.NET\my.config';
    ad := clr.CreateAppDomain('myNET', ads);
    obj := (ad as _AppDomain).CreateInstanceFrom('DelphiNET.dll', 'DelphiNET.NETAdder');
    ov := obj.Unwrap;
    Button1.Caption := 'done ' + string(ov.Add3(5));
  end;
  </code></pre>
  
  <p>This ends with error: <em>EOleError: Variant does not reference an automation object</em></p>
  
  <p>I have not worked with Delphi for a long time so I am stuck here...</p>
  
  <hr>
  
  <p><strong>Solution:</strong> There was problem in COM visibility which is not by default. This is the correct .NET assembly:</p>
  
  <pre><code>namespace DelphiNET
  {
      [ComVisible(true)]
      public class NETAdder
      {
          public int Add3(int left)
          {
              return left + 3;
          }
      }
  }
  </code></pre>
  
  <hr>
  
  <h1>Important note:</h1>
  
  <p>When working with .NET from Delphi, it is important calling <code>Set8087CW($133F);</code> at the beginning of your program (i.e. before <code>Application.Initialize;</code>). Delphi has enabled floating point exceptions by default (see <a href="http://digital.ni.com/public.nsf/allkb/E6A73825E57FCD9F862570DD005E594F" rel="nofollow noreferrer">this</a>) and the CLR doesn’t like them. When I had them enabled, my program weirdly freezed.</p>