您的位置:首页 > 编程语言 > Delphi

C#调用Delphi写的DLL

2011-01-19 15:14 387 查看
Delphi动态链接库中函数定义为:

function Get(s:PChar):Boolean;stdcall;


在C#中可以这样调用:

[DllImport(@"D:/Delphi/Test.dll", EntryPoint = "Get", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern bool Get(StringBuilder sb);

调用代码:

StringBuilder sb = new StringBuilder();
bool ret = Get(sb);
if (ret)
{
MessageBox.Show(sb.ToString());
}


这里需要注意的是要外传的PChar类型参数,在C#中对应使用StringBuilder,如果使用string没有任何信息传出,如果使用ref string形式,则会出现内存错误。

如果Delphi中函数的参数定义为var s :PChar类型,则相应的外传参数需要使用ref string类型,例如:
Delphi动态链接库中函数定义为:

function Get(var s:PChar):Boolean;stdcall;

在C#中可以这样调用:

[DllImport(@"D:/Delphi/Test.dll", EntryPoint = "Get", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern bool Get(ref string s);


调用代码:

string s = "";
bool ret = Get(ref s);
if (ret)
{
MessageBox.Show(s);
}


经过测试:
Delphi中Integer的参数使用C#中的int即可;
Delphi中Real的参数使用C#中的double即可;
Delphi中Boolean的参数使用C#中的bool即可;
Delphi中TDateTime的参数使用C#中的DateTime即可;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: