Search This Blog

Friday, December 18, 2009

Using unmanaged Delphi dlls in .NET

What to do if we have an old working Delphi code that is quite complex and well tested and at the same time and we need to use the same functionality in a new .NET application. Let it be for example a complex encryption/decryption functions.

Of course we can rewrite them in .NET, but why to waste time if we already have something ready and tested?
The easiest way is to create a Delphi dll, that can look like:

function EncodeString (ps: PChar): PChar; export; stdcall;
var
str: AnsiString;
begin
str := ps;
str := ExistingEncodeStringFunction(str);
Result := PChar(str);
end;

function DecodeString (ps: PChar): PChar; export; stdcall;
var
str: AnsiString;
begin
str := ps;
str := ExistingDecodeStringFuncion(str);
Result := PChar(str);
end;

exports
EncodeString, DecodeString;


Now we copy out Delphi dll into bin folder of our .NET project.
We add a class method with a DllImport decorator:

[DllImport("DelphiEncryption.dll", CharSet = CharSet.Ansi)]
static extern string DecodeString(String val);

We do the same for EncodeString, and now we are happy to use our existing Delphi code in .NET.

1 comment:

  1. And this is how it looks in Python:

    import ctypes

    dll_file = windll.DelphiEncryption
    print dll_file.EncodeString("some text")

    ReplyDelete