且构网

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

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

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

***的方法是使用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)