c# - 在 C# 中使用 Delphi DLL

标签 c# delphi dllimport

我有一个用 Delphi 编写的第三方“神秘 dll”(未知版本),Delphi 中的工作示例(过去 2009 年),迫切需要在我的 C# 代码中使用所述 dll,并且几乎没有关于如何做的相关知识.

以下是使用此 dll 的 Delpi 示例:

type
TD_Query = function(host: WideString; port : Word;pud,query : WideString):WideString; stdcall;
procedure TForm11.Button6Click(Sender: TObject);
var
   Handle         : LongWord;
   D_Query        : TD_Query;
   sss            : WideString;
begin

 Handle := LoadLibrary('kobrasdk.dll');
 sss:='';
 if Handle <> 0 then
 begin
  @D_Query := GetProcAddress(Handle, 'D_Query');
  sss:=D_Query('host',8201,'pud','query');
  FreeLibrary(Handle);
 end;
end;

这是我用 C# 解释它的尝试:

class Program
{
    [DllImport("C:\\Games\\kobrasdk.dll", CallingConvention = CallingConvention.StdCall,
        CharSet = CharSet.Ansi)]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern string D_Query(string host, ushort port, string pud, string query);


    static void Main(string[] args)
    {
        D_Query("test", 8201, "test", "test");
    }
}

不幸的是,我得到的是一个错误:试图读取或写入 protected 内存。这通常表明其他内存已损坏。

根据我白天阅读的内容,我可能搞砸了返回类型或参数类型。帮忙?

最佳答案

Delphi ABI 在某些类型上不同于 Microsoft ABI。 Delphi WideString 是一种托管类型(在 Delphi 术语中)并且作为返回类型使用与 Microsoft 工具不兼容的 ABI。

Delphi ABI 将托管返回类型转换为隐藏的 var 参数。所以编译器转换:

function(host: WideString; port: Word; pud, query: WideString): WideString; stdcall;

进入

procedure(var result: WideString; host: WideString; port: Word; pud, query: WideString); 
  stdcall;

因此,您可以通过以转换后的形式导入函数,从 C# 访问原始的 Delphi 函数。

[DllImport(@"...", CallingConvention = CallingConvention.StdCall)]
public static extern void My_D_Query(
    [MarshalAs(UnmanagedType.BStr)]
    out string result,
    [MarshalAs(UnmanagedType.BStr)]
    string host,
    ushort port,
    [MarshalAs(UnmanagedType.BStr)]
    string pud,
    [MarshalAs(UnmanagedType.BStr)]
    string query
);

关于c# - 在 C# 中使用 Delphi DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38208928/

相关文章:

c# - 是否可以解决 .Net 3.5 中的 "Default parameter specifiers are not permitted"错误?

multithreading - Delphi异步写入TListBox

Delphi 和 dll 版本

c# - 如何调用 scanf 而不是 Console.ReadLine()?

c# - xunit 添加信息到输出

c# - 签署 PDF 文档

delphi - TBitmap 在非相关图形代码后丢失剪切区域

c# - dllimport 和 getProcAddress 之间的区别

python - 动态重新加载 Cython 模块

c# - .NET Core 网站无法在 OS X 上构建 - "Assets file ' .../obj/project.assets.json' 未找到。”