将Pchar Delphi DLL导入C#?
作者:互联网
我在delphi中有一个过程:
procedure PasswordDLL(month integer; password pchar);
export;
该过程应该输入密码到我传入的“密码”pchar ..
从我的谷歌和阅读….
参考:HERE和HERE
我想出来:
[DllImport(
"DelphiPassword.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi,
EntryPoint = "PasswordDLL")]
public static extern void PasswordDLL(
int month,
[MarshalAs(UnmanagedType.LPStr)] string password
);
然后当我打电话:
string pass = "";
PasswordDLL(2, pass);
所以输出到“pass”字符串的密码.
但我将得到BadImageFormatException未处理:尝试加载具有不正确格式的程序. (HRESULT异常:0x80HEREB)
听起来我用过的函数格式错了吗?
我想知道我是否为PChar使用了不正确的UnmanagedType,但从阅读中,它是LPWStr和LPStr ..我错过了什么吗?
提前致谢…
解决方法:
首先,因为你还没有说明你使用哪个Delphi版本我会回答假设Delphi 6没有其他原因而不是我熟悉它.
您的Delphi过程未在其声明中指定调用约定,因此它不会根据您的导入使用stdcall.它将使用默认的Delphi寄存器约定,它将前几个参数放在寄存器中而不是堆栈中.如果你可以改变你的Delhpi DLL添加stdcall;在声明和重建之后,您的调用约定将匹配.
下表总结了调用约定.
Directive Parameter order Clean-up Passes parameters in registers?
--------- --------------- -------- -------------------------------
register Left-to-right Routine Yes
pascal Left-to-right Routine No
cdecl Right-to-left Caller No
stdcall Right-to-left Routine No
safecall Right-to-left Routine No
看看.NET文档似乎没有符合Delphi注册约定的调用约定(见下表),所以我认为你唯一的选择可能就是改变Delphi DLL中的约定.
Member name Description
----------- ------------------------
Cdecl The caller cleans the stack. This enables calling functions with varargs, which makes it appropriate to use for methods that accept a variable number of parameters, such as Printf.
FastCall This calling convention is not supported.
StdCall The callee cleans the stack. This is the default convention for calling unmanaged functions with platform invoke.
ThisCall The first parameter is the this pointer and is stored in register ECX. Other parameters are pushed on the stack. This calling convention is used to call methods on classes exported from an unmanaged DLL.
Winapi Supported by the .NET Compact Framework. This member is not actually a calling convention, but instead uses the default platform calling convention. For example, on Windows the default is StdCall and on Windows CE .NET it is Cdecl.
你的Delphi(6)Pchar(指向空终止的ANSI字符串的指针)编组看起来是正确的.
标签:c,delphi,pchar 来源: https://codeday.me/bug/20190704/1382039.html