如何在c#中使用delphi dll ?



我尝试在c#中调用delphi中编码的dll。(delphi 11 64bit)我相信会有一些问题。因此,我在这些网站上尝试了一些例子:从c#调用dll中的Delphi方法从c# .NET应用程序中调用Delphi DLL

但是没有响应,应用程序关闭。

这些是我的代码:

示例1

德尔福

function DBConnect1(inputStr,connStr:PWideChar):PWideChar;stdcall;
begin
try
result:=PWideChar('Hello from Delphi!');
except
result:=PWideChar('Exception');
end;
end;

c#

[DllImport("Project1.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string DBConnect1(string inputString, string connectionString);
string inputString = "Parker";
string connectionString = "MyComputer";
string dbStrObj1 = DBConnect1(inputString, connectionString);
MessageBox.Show(dbStrObj1);

示例2

德尔福

function Test1(sFD,sVD,sINI,sCh,sSD: string): PWideChar;stdcall;
var
tempStr:string;
str:WideString;
begin
tempStr:=sFD+sVD+sINI+sCh+sSD;
try
result:= PWideChar(tempStr);
except
str:='Error';
result:=PWideChar(str);
end;
result:=PWideChar(str);
end;

c#

[DllImport("Project1.dll", EntryPoint = "LoginLic", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string LoginLic(string s1, string s2, string s3, string s4, string s5);
string strId = "PCMS";
string strVersion = "AD19";
string strIni = @"";
string strCheck = "0";
string strSubDate = null;
string aa;
aa = UseDll.LoginLic(strId, strVersion, strIni, strCheck, strSubDate);

还必须编排函数参数。请参考此链接,通过封送传递字符串https://learn.microsoft.com/en-us/dotnet/framework/interop/default-marshalling-for-strings

[DllImport("Project1.dll",CallingConvention = CallingConvention.StdCall,CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string DBConnect1(MarshalAs(UnmanagedType.LPWStr)]string inputString, MarshalAs(UnmanagedType.LPWStr)] string connectionString);

最新更新