如何将Delphi字符串传递给Prism DLL? [英] How can I pass a Delphi string to a Prism DLL?

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

问题描述

我们尝试将一个字符串从一个本机Delphi程序传递给一个Delphi Prism DLL。
我们传递整数没有问题,但DLL中的字符串不匹配。
我们在回复中看到罗伯特·爱的代码片段对于另一个问题,但是没有本地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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆