从C# .NET应用程序调用Delphi DLL

34

编辑:我已经发布了更好的实现方法,请往下看。我在这里留下这个,以便回复是有意义的。

我已经做过许多搜索,寻找在Delphi中编写DLL并能够从C#中调用它、传递和返回字符串的正确方法。很多信息都是不完整或不正确的。经过多次尝试,我找到了解决方案。

这是使用Delphi 2007和VS 2010编译的。我认为它在其他版本中也可以正常工作。

以下是Delphi代码。记得在项目中包含版本信息。

library DelphiLibrary;

uses SysUtils;

// Compiled using Delphi 2007.

// NOTE: If your project doesn't have version information included, you may
// receive the error "The "ResolveManifestFiles" task failed unexpectedly"
// when compiling the C# application.

{$R *.res}

// Example function takes an input integer and input string, and returns
// inputInt + 1, and inputString + ' ' + IntToStr(outputInt) as output
// parameters. If successful, the return result is nil (null), otherwise it is
// the exception message string.


// NOTE: I've posted a better version of this below. You should use that instead.

function DelphiFunction(inputInt : integer; inputString : PAnsiChar;
                        out outputInt : integer; out outputString : PAnsiChar)
                        : PAnsiChar; stdcall; export;
var s : string;
begin
  outputInt := 0;
  outputString := nil;
  try
    outputInt := inputInt + 1;
    s := inputString + ' ' + IntToStr(outputInt);
    outputString := PAnsiChar(s);
    Result := nil;
  except
    on e : exception do Result := PAnsiChar(e.Message);
  end;
end;

// I would have thought having "export" at the end of the function declartion
// (above) would have been enough to export the function, but I couldn't get it
// to work without this line also.
exports DelphiFunction;

begin
end.

以下是C#代码:

using System;
using System.Runtime.InteropServices;

namespace CsharpApp
{
    class Program
    {
        // I added DelphiLibrary.dll to my project (NOT in References, but 
        // "Add existing file"). In Properties for the dll, I set "BuildAction" 
        // to None, and "Copy to Output Directory" to "Copy always".
        // Make sure your Delphi dll has version information included.

        [DllImport("DelphiLibrary.dll", 
                   CallingConvention = CallingConvention.StdCall, 
                   CharSet = CharSet.Ansi)]
        public static extern 
            string DelphiFunction(int inputInt, string inputString,
                                  out int outputInt, out string outputString);

        static void Main(string[] args)
        {
            int inputInt = 1;
            string inputString = "This is a test";
            int outputInt;
            string outputString;


// NOTE: I've posted a better version of this below. You should use that instead.


            Console.WriteLine("inputInt = {0}, intputString = \"{1}\"",
                              inputInt, inputString);
            var errorString = DelphiFunction(inputInt, inputString,
                                             out outputInt, out outputString);
            if (errorString != null)
                Console.WriteLine("Error = \"{0}\"", errorString);
            else
                Console.WriteLine("outputInt = {0}, outputString = \"{1}\"",
                                  outputInt, outputString);
            Console.Write("Press Enter:");
            Console.ReadLine();
        }
    }
}

我希望这些信息能够帮助其他人,让他们不必像我一样抓狂。


不是一个问题,但是+1 :)。 - Jesper Fyhr Knudsen
我不熟悉Delphi,但是如果可以将其转换为COM,那么在C#中使用它就很容易了。我进行了一些搜索,并找到了一些关于Delphi和COM关系的资源,网址在这里:http://delphi.about.com/library/weekly/aa122804a.htm - Saeed Amiri
6
请将您的问题重新表述为“如何正确地在C# .NET应用程序中使用Delphi DLL?”,然后在您的帖子中回答自己。请参考http://stackoverflow.com/faq(您可以回答自己的问题)和http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions。 - Jens Mühlenhoff
8
在这里你需要非常小心。Delphi字符串是引用计数的;在DelphiFunction函数结束时,s的引用计数将为零,因此s所使用的内存将返回给内存分配器,并且在C#调用程序可以获取内容之前可能会被其他内容使用(和覆盖)。当发生这种情况时,各种破坏将会发生。在多线程情况下(特别是在多核系统上),这可能会很快发生。 - Jeroen Wiert Pluimers
Jens - 感谢您提供的信息。我在想我是否做得对。- Dan - Dan Thomas
5个回答

29

根据我发布的帖子的回复,我创建了一个新的示例,使用字符串缓冲区返回字符串,而不仅仅是返回PAnsiChars。

Delphi DLL源代码:

library DelphiLibrary;

uses SysUtils;

// Compiled using Delphi 2007.

// NOTE: If your project doesn't have version information included, you may
// receive the error "The "ResolveManifestFiles" task failed unexpectedly"
// when compiling the C# application.

{$R *.res}

// A note on returing strings. I had originally written this so that the
// output string was just a PAnsiChar. But several people pointed out that
// since Delphi strings are reference-counted, this was a bad idea since the
// memory for the string could get overwritten before it was used.
//
// Because of this, I re-wrote the example so that you have to pass a buffer for
// the result strings. I saw some examples of how to do this, where they
// returned the actual string length also. This isn't necessary, because the
// string is null-terminated, and in fact the examples themselves never used the
// returned string length.


// Example function takes an input integer and input string, and returns
// inputInt + 1, and inputString + ' ' + IntToStr(outputInt). If successful,
// the return result is true, otherwise errorMsgBuffer contains the the
// exception message string.
function DelphiFunction(inputInt : integer;
                        inputString : PAnsiChar;
                        out outputInt : integer;
                        outputStringBufferSize : integer;
                        var outputStringBuffer : PAnsiChar;
                        errorMsgBufferSize : integer;
                        var errorMsgBuffer : PAnsiChar)
                        : WordBool; stdcall; export;
var s : string;
begin
  outputInt := 0;
  try
    outputInt := inputInt + 1;
    s := inputString + ' ' + IntToStr(outputInt);
    StrLCopy(outputStringBuffer, PAnsiChar(s), outputStringBufferSize-1);
    errorMsgBuffer[0] := #0;
    Result := true;
  except
    on e : exception do
    begin
      StrLCopy(errorMsgBuffer, PAnsiChar(e.Message), errorMsgBufferSize-1);
      Result := false;
    end;
  end;
end;

// I would have thought having "export" at the end of the function declartion
// (above) would have been enough to export the function, but I couldn't get it
// to work without this line also.
exports DelphiFunction;

begin
end.

C# 代码:

using System;
using System.Runtime.InteropServices;

namespace CsharpApp
{
    class Program
    {
        // I added DelphiLibrary.dll to my project (NOT in References, but 
        // "Add existing file"). In Properties for the dll, I set "BuildAction" 
        // to None, and "Copy to Output Directory" to "Copy always".
        // Make sure your Delphi dll has version information included.

        [DllImport("DelphiLibrary.dll", 
                   CallingConvention = CallingConvention.StdCall, 
                   CharSet = CharSet.Ansi)]
        public static extern bool 
            DelphiFunction(int inputInt, string inputString,
                           out int outputInt,
                           int outputStringBufferSize, ref string outputStringBuffer,
                           int errorMsgBufferSize, ref string errorMsgBuffer);

        static void Main(string[] args)
        {
            int inputInt = 1;
            string inputString = "This is a test";
            int outputInt;
            const int stringBufferSize = 1024;
            var outputStringBuffer = new String('\x00', stringBufferSize);
            var errorMsgBuffer = new String('\x00', stringBufferSize);

            if (!DelphiFunction(inputInt, inputString, 
                                out outputInt,
                                stringBufferSize, ref outputStringBuffer,
                                stringBufferSize, ref errorMsgBuffer))
                Console.WriteLine("Error = \"{0}\"", errorMsgBuffer);
            else
                Console.WriteLine("outputInt = {0}, outputString = \"{1}\"",
                                  outputInt, outputStringBuffer);

            Console.Write("Press Enter:");
            Console.ReadLine();
        }
    }
}

这里还有一个额外的类,展示了如何动态加载DLL(抱歉代码行很长):

using System;
using System.Runtime.InteropServices;

namespace CsharpApp
{
    static class DynamicLinking
    {
        [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        static extern bool FreeLibrary(int hModule);

        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        delegate bool DelphiFunction(int inputInt, string inputString,
                                     out int outputInt,
                                     int outputStringBufferSize, ref string outputStringBuffer,
                                     int errorMsgBufferSize, ref string errorMsgBuffer);

        public static void CallDelphiFunction(int inputInt, string inputString,
                                              out int outputInt, out string outputString)
        {
            const string dllName = "DelphiLib.dll";
            const string functionName = "DelphiFunction";

            int libHandle = LoadLibrary(dllName);
            if (libHandle == 0)
                throw new Exception(string.Format("Could not load library \"{0}\"", dllName));
            try
            {
                var delphiFunctionAddress = GetProcAddress(libHandle, functionName);
                if (delphiFunctionAddress == IntPtr.Zero)
                    throw new Exception(string.Format("Can't find function \"{0}\" in library \"{1}\"", functionName, dllName));

                var delphiFunction = (DelphiFunction)Marshal.GetDelegateForFunctionPointer(delphiFunctionAddress, typeof(DelphiFunction));

                const int stringBufferSize = 1024;
                var outputStringBuffer = new String('\x00', stringBufferSize);
                var errorMsgBuffer = new String('\x00', stringBufferSize);

                if (!delphiFunction(inputInt, inputString, out outputInt,
                                    stringBufferSize, ref outputStringBuffer,
                                    stringBufferSize, ref errorMsgBuffer))
                    throw new Exception(errorMsgBuffer);

                outputString = outputStringBuffer;
            }
            finally
            {
                FreeLibrary(libHandle);
            }
        }
    }
}

-Dan


我正在尝试将上述动态版本与一个我没有源代码的Delphi过程一起使用,但我知道该函数具有空返回并接受单个布尔值作为参数。当我运行它时,我会收到PInvokeStackImbalance异常。我可以将C#布尔值传递给Delphi过程,还是必须将其转换为另一种类型,例如字节? - Kevin S. Miller

5
如Jeroen Pluimers在他的评论中所说,你应该注意Delphi字符串是引用计数的。
在这种情况下,当你需要在异构环境中返回一个字符串时,你应该要求调用者提供结果的缓冲区,并且函数应该填充该缓冲区。这样,调用者就负责创建缓冲区并在使用完毕后将其处理掉。如果你查看Win32 API函数,你会发现它们在需要向调用者返回一个字符串时也会这样做。
为此,你可以使用PChar(PAnsiChar或PWideChar)作为函数参数的类型,但你还应该要求调用者提供缓冲区的大小。请参阅下面链接中我的答案,其中包含一个示例源代码: 在FreePascal编译的DLL和Delphi编译的EXE之间交换字符串(PChar) 问题特别针对在FreePascal和Delphi之间交换字符串,但这个想法和答案也适用于你的情况。

感谢你们两位指出这个问题 - 这是一种潜在的错误,可能需要很长时间才能排除。我心里一直在想这个问题,但我没有足够关注那个理性的小声音。真是我的错。;p 我在下面发布了一个更好的示例,解决了这个问题。 - Dan Thomas
在我的测试中,我发现将StrNew(PChar(s))的结果返回不会像GetMem-> StrPLCopy那样产生错误,这样是否更安全? - Jamie Kitson

3
在 Delphi 2009 中,如果您将变量 s 明确声明为 AnsiString,则代码的运行效果会更好,例如:

var s: AnsiString;

var s : Ansistring;

在调用后,从C#中得到预期的结果:

outputInt = 2, outputString = "This is a test 2"

替代

outputInt = 2, outputString = "T"

0

使用PString更容易检索字符串:

function DelphiFunction(inputString : PAnsiChar;
                    var outputStringBuffer : PString;
                    var errorMsgBuffer : PString)
                    : WordBool; stdcall; export;
var 
  s : string;
begin
  try
    s := inputString;
    outputStringBuffer:=PString(AnsiString(s));
    Result := true;
  except
    on e : exception do
    begin
      s:= 'error';
      errorMsgBuffer:=PString(AnsiString(e.Message));
      Result := false;
    end;
  end;
end;

在C#中:

    const int stringBufferSize = 1024;

    var  str = new    IntPtr(stringBufferSize);

    string loginResult = Marshal.PtrToStringAnsi(str);

1
你正在返回指向堆栈上的局部变量的指针。一旦DelphiFunction返回,该变量将不再有效。它可能仍然能运行,但是你不应该依赖它。 - dan-gph

0
如果在2022年或之后遇到此错误,请使用VisualStudio 2010编译DLLImport和P / Invoke操作,未来版本(可能除了Visual Studio 2012)不允许从Delphi中加载托管代码到针对x64机器系统的C#应用程序中,该应用程序来自一个非托管的x86 DLL库。在处理/导出RAD Studio和Delphi编译器时,请改用.Net Framework 4.0而不是.Net Framework 4.8或更高版本,同时避免使用.Net Core,Standard和.Net。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接