本文介绍了如何将 Delphi 字符串传递给 Prism DLL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们尝试将字符串从原生 Delphi 程序传递到 Delphi Prism DLL.我们传递整数没有问题,但字符串在 DLL 中不匹配.我们在回答另一个问题时看到了 Robert Love 的代码片段,但是没有原生Delphi程序的代码.

We try to pass a string from a native Delphi program to a Delphi Prism DLL.We have no problem passing integers, but strings are mismatched in the DLL.We saw Robert Love's code snippet in response to another question, but there is no code for the native Delphi program.

我们如何将字符串从 Delphi 传递到 Delphi Prism DLL?

How can we pass strings from Delphi to a Delphi Prism DLL?

推荐答案

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

这篇关于如何将 Delphi 字符串传递给 Prism DLL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 21:44