The pile is damaged. C # dllimport, delphi Return value of PChar

I imported the dll. All other parts work, but the return value of the string of the imported method gives the following:

Unhandled exception in 0x7748EA5F (ntdll.dll) in ***. exe: 0xC0000374: the heap is corrupted (parameters: 0x774C4270).

It still returns a string, but I'm worried that it causes some other errors later, which are difficult to debug. From what I tested, it seems like it could be anything that causes this.

This is my import 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));

Using

getString(Handle, 1);

This works, but causes an error. During debugging, simply by clicking "continue", you can process it and show the results. The result is correct.

Here's how to do it in delphi dll

function GetString(Hnd,Index : Integer) : PChar; stdcall;
begin
 Result:=TControl(Hnd).Stack.GetString(Index);
end;

, doubleles, bools dll, . , .

. , , , (ctrl + f5), , . , .

TL; DR; , , ints, bools .. .

+4
1

p/invoke, . , COM, . CoTaskMemAlloc. .

  • Delphi, .
  • IntPtr Marshal.PtrToStringAnsi . , , , .
  • COM BSTR, Delphi out, . . WideString ?
  • .

, , PChar(s), s - . , .

, ( ) , . , .

+8

Source: https://habr.com/ru/post/1588985/


All Articles