Delphi调用C#生成的DLL
四月 5, 2010 at 6:38 下午
—
Easton
You were definitely closer with your second attempt as you can't load a .NET assembly as if it was a normal C-style DLL. If you're getting "Class not registered" error messages in Delphi it simply means the required registry entries were not available.
To use your C# class as a COM object, the best thing to do is put all your methods in one or more interfaces then make the class implement each of those interfaces.
Example:
// IAddInterface.cs
public interface IAddInterface
{
int Add(int i1, int i2);
}
// SimpleDll.cs
using System.Runtime.InteropServices;
[ClassInterface(ClassInterfaceType.None)]
public class SimpleDLL : IAddInterface
{
public int Add(int i1, int i2)
{
return i1+i2;
}
}
Compile using:
csc /t:library /out:SimpleDll.dll *.cs
Next, register the assembly as a COM object in the registry using:
regasm SimpleDll.dll /tlb:Add.tlb
(The above command will also generate a type library for use in Delphi.)
Now you can switch over to Delphi, and click Project->Import Type Library (like you did before). Select your .tlb (Add.tlb in this case) and click Create Unit.
In your main unit add "ComObj" and "SimpleDLL_TLB" (or whatever your generated unit is called) to your uses list and write the code to call your .NET methods.
Example:
procedure TForm1.Button1Click(Sender: TObject);
var
intfRef: IAddInterface;
result: Integer;
begin
intfRef := CreateComObject(CLASS_SimpleDLL_) as IAddInterface;
result := intfRef.Add(2, 2);
fd3e2cab-eb24-48f7-9d3e-9afeeff02cca|0|.0|96d5b379-7e1d-4dac-a6ba-1e50db561b04
Posted in: 技术文章
Tags: Delphi, C#, DLL