How can I pass a Delphi string to a Prism DLL?

ぃ、小莉子 提交于 2019-11-27 23:16:54

The best way would be to use WideString.

For several reasons.

  • It is Unicode and works before D2009
  • It's memory is managed in ole32.dll, so no dependency on either Delphi's memory manager or the CLR GC.
  • You do not have to directly deal with pointers

In Oxygene, you could write it like so:

type
  Sample = static class
  private
    [UnmanagedExport]
    method StringTest([MarshalAs(UnmanagedType.BStr)]input : String;
                      [MarshalAs(UnmanagedType.BStr)]out output : String);
  end;

implementation

method Sample.StringTest(input : String; out output : String);
begin
  output := input + "ä ~ î 暗";
end;

"MarshalAs" tells the CLR how to marshal strings back and forth. Without it, strings are passed as Ansi (PAnsiChar), which is probably NOT what you would want to do.

This is how to use it from Delphi:

procedure StringTest(const input : WideString; out output : WideString);
  stdcall; external 'OxygeneLib';

var
  input, output : WideString;
begin
  input := 'A b c';
  StringTest(input, output);
  Writeln(output);
end.

Also, never ever use types, that are not clearly defined, for external interfaces. You must not use PChar for DLL imports or exports. Because if you do, you will run into exceptions when you compile it with D7 or D2009 (depending on what the original dev system was)

Strings in Delphi Win32 are managed differently from strings in .Net, so you can not pass a .Net string to Delphi Win32 or vice versa.

To exchange strings values you'd better use PChar type which is supported by both compilers. That is the same way you send string values to Windows API functions.

Regards

P.S. I am NOT Robert ;-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!