在C#中使用Delphi DLL [英] Using Delphi DLL in C#
问题描述
我有一个用Delphi(未知版本)编写的第三方神秘dll,这是delphi中的工作示例(过去2009),迫切需要在我的C#代码中使用所说的dll,并且几乎没有相关的知识来做到这一点。
I have a third party "mystery dll" written with Delphi(unknown version), working example in delphi (past 2009), dire need to use said dll in my C# code, and almost no relevant knowledge on how to do it.
下面是使用此dll的Delpi示例:
Here is Delpi example in using this dll:
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#中解释它的尝试:
And here is my attempts to interpret it in 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");
}
}
不幸的是,我有一个错误:试图读取或写入受保护的内存。通常这表明其他内存已损坏。
Unfortunately, what I have is an error: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
根据我白天的读物,我可能对返回类型或参数类型有所怀疑。
From what I read during the day, I probably fudged up with return type, or parameter types. Help?
推荐答案
Delphi ABI在某些类型上不同于Microsoft ABI。 Delphi WideString
是托管类型(在Delphi术语中),而返回类型使用与Microsoft工具不兼容的ABI。
The Delphi ABI differs from the Microsoft ABI for certain types. A Delphi WideString
is a managed type (in Delphi terminology) and as return types use an ABI that is incompatible with Microsoft tools.
Delphi ABI将托管返回类型转换为隐藏的 var
参数。因此编译器将转换为:
The Delphi ABI translates a managed return type into a hidden var
parameter. So the compiler transforms:
function(host: WideString; port: Word; pud, query: WideString): WideString; stdcall;
进入
procedure(var result: WideString; host: WideString; port: Word; pud, query: WideString);
stdcall;
因此,您可以通过以转换后的形式导入C#来访问原始的Delphi函数。
You can therefore access your original Delphi function from C# by importing the function in its transformed guise.
[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#中使用Delphi DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!