I've written a Dll with C# with an exported function that save a file.
Here's the C# code
using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
namespace ClassLibrary1
{
public class Class1
{
[DllExport("Funcion", CallingConvention = CallingConvention.StdCall)]
public static void Funcion(IntPtr pDataIn, Int32 pSize, [Out, MarshalAs(UnmanagedType.I4)] int pArchivo)
{
byte[] documento = new byte[pSize];
Marshal.Copy(pDataIn, documento, 0, pSize);
File.WriteAllBytes("Document2.pdf", documento);
pArchivo = 25;
}
}
}
In Delphi, I load the library and call the exported function and it works fine.
Here's the Delphi Code
procedure TForm1.Button1Click(Sender: TObject);
var
lStream : TMemoryStream;
lArBytes : array of Byte;
lInDocSize : Integer;
lHndle : THandle;
Funcion : procedure(pDataIn : array of Byte;
pInSize : Integer;
var pDocumento : Integer
); stdcall;
begin
try
lHndle := LoadLibrary('ClassLibrary1.dll');
if (lHndle <> 0) then
begin
Funcion := GetProcAddress(lHndle, 'Funcion');
if Assigned(Funcion) then
begin
try
lStream := TMemoryStream.Create;
lStream.LoadFromFile('Document1.PDF');
lStream.Position := 0;
SetLength(lArBytes, lStream.Size);
lStream.Read(lArBytes[0], lStream.Size);
lInDocSize := 0;
Funcion(lArBytes, lStream.Size, lInDocSize);
Label1.Caption := IntToStr(lInDocSize);
except on E : Exception do
begin
RaiseLastOSError;
ShowMessage(e.Message);
end;
end;
end;
end;
finally
end;
end;
I have an error with the output parameter, it is that always returns cero (0) value, not matter what value I assign to parameter, it always has cero value.
I've changing the parameter like this
out int pArchivo
and
ref int pArchivo
But when the function finish I get a memory exception.
With Marshal, function finish fine, without memory errors, but the output paramerter value is always cero (0).
[Out, MarshalAs(UnmanagedType.I4)] int pArchivo
I've read about this problem in this post in Stackoverflow
Passing array of struct from c# to Delphi
But in my case, it doesn't work
What I'm doing wrong?
I hope that you could help... thank you so much