Steve
Steve

Reputation: 41

Delphi dll function to C#

With a compiled Delphi dll, one of the functions declared is

Mydll.dll

type
 TInfo = array [0..255] of byte;

type
 public
   function GetInfo(Memadr, Infolen: Integer): TInfo;

what is the DLLImport format to use this in C#?

Upvotes: 2

Views: 803

Answers (2)

Steve
Steve

Reputation: 1

Need to correct an error in my original post,

type
 TInfo = array [0..255] of byte;

implementation
 function GetInfo(Memadr, Infolen: Integer): TInfo;


procedure TForm1.Button5Click(Sender: TObject);
var Data: TInfo;
    i: integer;
    s: string;
begin
for i:=0 to 255 do Data[i]:=0;
Data:=GetInfo($04,12);
if (Data[1]=0) then
  begin StatusBar1.SimpleText:='No Data'; exit; end;
s:='';
for i:=1 to 8 do
  s:=s+Chr(Data[i+1]);
Edit3.Text:=s;
end;

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613441

I'd do it like this:

Delphi

type
  TInfo = array [0..255] of byte;

procedure GetInfo(Memadr, Infolen: Integer; var Result: TInfo); stdcall;

C#

[DllImport(@"testlib.dll")]
static extern void GetInfo(int Memadr, int Infolen, byte[] result);

static void Main(string[] args)
{
    byte[] result = new byte[256];
    GetInfo(0, result.Length, result);
    foreach (byte b in result)
        Console.WriteLine(b);
}

You need to get the calling conventions to match. I've gone for stdcall which is the default for P/invoke (that's why it's not specified in the P/invoke signature).

I'd avoid returning the array as a function return value. It's easier to marshall it this way as a parameter.

In fact in general, if you want to get away from fixed size buffers you could do it like this:

Delphi

procedure GetInfo(Memadr, Infolen: Integer; Buffer: PByte); stdcall;

Then, to fill out the buffer, you'd need to use some pointer arithmetic or something equivalent.

Upvotes: 4

Related Questions