0

Sorry, if it is a dumb question, I am pretty new to Delph, and struggling with basics. Below is the Delphi code and I call the same from C#, but it gives an error as "System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'"

function GetString(str: PWideChar; len: Integer): Integer; stdcall;
begin
  StrLCopy(str, 'hello world', len);
  Result := 1; // real code would have real error handling
end;
exports GetString;

C# code

[DllImport("AppLoader.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern int GetString(StringBuilder str, int len);

private void button3_Click(object sender, EventArgs e)
{
     StringBuilder str = new StringBuilder(256);
     int retval = GetString(str, str.Capacity);
     MessageBox.Show(str.ToString());
}
Sam K
  • 332
  • 1
  • 6
  • 19
  • Delphi strings are incompatible with others and use own memory manager, so it is impossible to make DLL function with string arguments/result for using with another languages. Consider using of BSTR (Delphi WideString) or PWideChar types. – MBo Apr 25 '20 at 06:09
  • Thank you MBo, I tried PWideChar as well but, still it's the same issue function TestFunction(out outputStr : PWideChar): PWideChar ; stdcall; – Sam K Apr 25 '20 at 06:18
  • It interests me that you thought to map a string return value on to C# bool. It looks like you are using trial and error. Have a read of the posts I linked to, and many other similar ones. That will help. – David Heffernan Apr 25 '20 at 07:16
  • Hi David, i modified the code as above and it still doesn't work – Sam K Apr 25 '20 at 07:21
  • No. But then you didn't follow the advice given. I helpfully provided multiple duplicate topics. I suggest that you read them. – David Heffernan Apr 25 '20 at 08:14
  • I modified the code as per your direction. This works fine when I have C# and Delphi compiled in 64Bit, but it doesn't work When I compile both in 32 Bit – Sam K Apr 25 '20 at 11:27
  • Should work fine in 32 bit. Make sure you recompile everything. If you want to make it possible for people to help you, don't every say "it doesn't work". Explain how it fails in detail. – David Heffernan Apr 25 '20 at 11:43
  • I recompiled Delphi DLL in Windows-32 bit and set my C# project to x86 – Sam K Apr 25 '20 at 12:09

0 Answers0