I have dll imported. All the other parts work, but the string return value of imported method gives this:
Unhandled exception at 0x7748EA5F (ntdll.dll) in ***.exe: 0xC0000374: A heap has been corrupted (parameters: 0x774C4270).
It still returns the string, but I'm worried that this causes some other errors later on, that are hard to debug. From what I have tested, it feels like it can be anything, that is causing this.
This is my importing code:
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
private delegate String GetStringDelegate(int handle, int index);
private static GetStringDelegate getString { get; set; }
var addressOfGetString = NativeMethods.GetProcAddress(_handle, "GetString");
getString = (GetStringDelegate)Marshal.GetDelegateForFunctionPointer(addressOfGetString, typeof(GetStringDelegate));
usage
getString(Handle, 1);
This works, but it causes the error. While debugging, just pressing "continue" will allow it to process it and show the results. Result is correct.
This is how it is done in delphi dll
function GetString(Hnd,Index : Integer) : PChar; stdcall;
begin
Result:=TControl(Hnd).Stack.GetString(Index);
end;
I have same kind of code for integers, doubles, bools and everything else in the dll works, without errors. So I think it creates somekind of overflow or wrong size of memory allocation.
Note: If I create console application, it just fails, without breaking on error, if I run console without debugger ( ctrl+f5 ), it works, still without error. Heap error is generated when I call this from forms application.
TL;DR; This code works, but it shows the heap error, while returning ints, bools etc works perfectly.
PCHAR
is Unicode in recent versions of Delphy, so[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
should be[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
– PiwowarCharSet.Ansi
is appropriate for this DLL – Jessabell