如何在 C# 中创建 DLL 并在 Delphi XE6 中调用

How to Create DLL in C# and call in Delphi XE6

我使用 File/New Project/Class 库在 VS2013 中创建了一个 DLL。然后我尝试在 Delphi 中动态加载它。但是 Delphi 正在为过程 GetProcAddress 返回 NIL

我的 C# 和 Delphi 代码看起来像我在下面发布的代码。在代码中 GetProcAddress 返回 NIL。如果我遗漏了什么,请告知。

C#代码

using System;
namespace TestDLL
{
    public class Class1
    {
        public static string EchoString(string eString)
        {
            return eString;
        }
    }
}

Delphi代码

 Type
    TEchoString = function (eString:string) : integer;stdcall;

  function TForm1.EchoString(eString:string):integer;
  begin
    dllHandle := LoadLibrary('TestDLL.dll') ;
    if dllHandle <> 0 then
    begin
      @EchoString := GetProcAddress(dllHandle, 'EchoString') ;
      if Assigned (EchoString) then
            EchoString(eString)  //call the function
      else
        result := 0;
      FreeLibrary(dllHandle) ;
    end
    else
    begin
      ShowMessage('dll not found ') ;
   end;
end;

C# DLL 是托管程序集,不会通过经典 PE 导出来导出其功能。您的选择:

  1. 使用 C++/CLI 混合模式包装 C#。然后,您可以按照通常的方式在非托管模式下导出函数。
  2. 使用 Robert Giesecke 的 UnmanagedExports。这可能比 C++/CLI 包装器更方便。
  3. 将托管功能公开为 COM 对象。

一旦您选择了这些选项之一,您将不得不处理对 string 数据类型的误用。这是对互操作无效的私有 Delphi 数据类型。对于问题中的简单示例 PWideChar 就足够了。