从Delphi调用dotNET并返回一个字符串 [英] Call dotNET from Delphi and return a string

查看:63
本文介绍了从Delphi调用dotNET并返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Delphi应用程序如何调用导出的功能(非COM)dotNET程序集并使该功能返回字符串?

How does a Delphi application call an exported function (non-COM) dotNET assembly and have the function return a string?

COM对于我的特定应用程序不是可行的解决方案.我可以控制通话的两端.

COM is not a possible solution for my particular application. I have control over both ends of the call.

type
  TStrProc = procedure( var x: widestring); stdcall;

function TryIt: string;
var
  Handle: THandle;
  Proc: TStrProc;
  InData: widestring;
  OutData: widestring;
begin
  Handle    := LoadLibrary( 'DelphiToDotNet.dll');
  if Handle = 0 then exit;
  @Proc := GetProcAddress( Handle, 'StrProc');
  if @Proc <> nil then
    begin
    InData := 'input';
    Proc( InData);
    OutData := InData;
    end;
  FreeLibrary( Handle);
  result := OutData
end;

dotNET dll端

public class DotNetDllClass
{
  [DllExport]
  public static string StrProc(ref string s)
  {
      return "Hello from .Net " + s;
  }
}

什么有效

我可以成功地将整数传入和传出dotNET过程.我可以成功地将字符串(Delphi端的宽字符串)传递到dotNET过程中.

What works

I can successfully pass integers into and out of dotNET procedures. I can successfully pass strings (widestring on the Delphi side) into dotNET procedures.

在上面的两个清单中,返回的字符串参数是垃圾.访问它会导致AV.

In the above two listings, the string parameter returned is junk. Accessing it causes an AV.

Delphi XE7,dotNET 4,Win 7、32位应用程序和dll.

Delphi XE7, dotNET 4, Win 7, 32 bit application and dll.

推荐答案

与Delphi相匹配的C#代码应为:

The C# code to match the Delphi should be:

[DllExport]
public static void StrProc(
    [MarshalAs(UnmanagedType.BStr)] 
    ref string s
)
{
    s = "Hello from .Net " + s;
}

请注意,返回类型为 void 以匹配您的Delphi代码.而且我使用了 UnmanagedType.BStr 来匹配 WideString .这是封送文本的最简单方法,因为分配是由两个编译器自动为您执行的.

Note that the return type is void to match your Delphi code. And I've used UnmanagedType.BStr to match WideString. That's the simplest way to marshal text since the allocation is performed automatically for you by the two compilers.

不要试图将字符串作为返回值编组为 BStr .Delphi不使用与其他编译器相同的ABI,请参见

Don't get caught out by trying to pass a string as a return value marshaled as a BStr. Delphi doesn't use the same ABI as other compilers, see Why can a WideString not be used as a function return value for interop?

这篇关于从Delphi调用dotNET并返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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