且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Delphi 字符串传递给 Prism DLL?

更新时间:2023-02-12 16:52:29

***的方法是使用 WideString.

The best way would be to use WideString.

出于多种原因.

  • 它是 Unicode 并且在 D2009 之前工作
  • 它的内存在 ole32.dll 中管理,因此不依赖于 Delphi 的内存管理器或 CLR GC.
  • 你不必直接处理指针

在 Oxygene 中,你可以这样写:

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"告诉 CLR 如何来回编组字符串.没有它,字符串将作为 Ansi (PAnsiChar) 传递,这可能不是您想要做的.

"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.

这是从 Delphi 中使用它的方法:

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.

此外,永远不要将未明确定义的类型用于外部接口.不得将 PChar 用于 DLL 导入或导出.因为如果你这样做,你用D7或D2009编译时会遇到异常(取决于原来的开发系统是什么)

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)