delphi - DLL 调用在 Delphi 2010 中有效,但 AV 在 Delphi XE2 中有效

标签 delphi dll delphi-xe2

我正在尝试使用 Delphi XE2 调用使用 Delphi 7(在 unicode 支持之前)构建的 DLL。 代码是这样的:

function Foo(Param1: PChar; Var Param2: DWORD; Var Param3: DWORD): PChar; stdcall; external 'bar.dll';

然后我打电话:

var
  V1: PChar;
  V2: AnsiString;
  V3, V4: DWORD;

begin
  V1 := Foo(PChar(V2), V3, V4);
  ..

此代码在 Delphi 2010 中有效,但在 XE2 中,我遇到以下堆栈的访问冲突:

System.UTF8ToUnicodeString(nil)
System.UTF8ToString(nil)
System.TObject.ClassName
Vcl.Forms.IsClass(???,Exception)
Vcl.Forms.TApplication.HandleException($2083120)
Vcl.Controls.TWinControl.MainWndProc(???)
System.Classes.StdWndProc(726196,273,6106,2365402)
:776e77d8 ; C:\Windows\SysWOW64\user32.dll
:776e78cb ; C:\Windows\SysWOW64\user32.dll
:776ef139 ; C:\Windows\SysWOW64\user32.dll
:776eaaa6 user32.SendMessageW + 0x52
:749fb322 ; C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.9200.16579_none_8937eec6860750f5\comctl32.dll
:749fb27e ; C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.9200.16579_none_8937eec6860750f5\comctl32.dll
:776e77d8 ; C:\Windows\SysWOW64\user32.dll
:776e78cb ; C:\Windows\SysWOW64\user32.dll
:776ebd11 user32.ChangeWindowMessageFilterEx + 0x71
:776ebd39 user32.CallWindowProcW + 0x1c
Vcl.Controls.TWinControl.DefaultHandler(???)
:0048b0c1 TWinControl.DefaultHandler + $DD
:0048afc4 TWinControl.WndProc + $5B8
:0049d031 TButtonControl.WndProc + $71
:004535f2 StdWndProc + $16
:776e77d8 ; C:\Windows\SysWOW64\user32.dll
:776e78cb ; C:\Windows\SysWOW64\user32.dll
:776e899d ; C:\Windows\SysWOW64\user32.dll
:776e8a66 user32.DispatchMessageW + 0x10

最佳答案

PChar 在 D7 中映射到 PAnsiChar,但在 D2009 及更高版本中映射到 PWideChar。您使用 AnsiString 而不是 UnicodeString 的做法是正确的,但您无法将 AnsiString 类型转换为 PWideChar >。您需要将其类型转换为 PAnsiChar,并且需要更改 D2009+ 中的 DLL 函数声明以匹配 DLL 实际使用的 PAnsiChar:

function Foo(Param1: PAnsiChar; var Param2: DWORD; var Param3: DWORD): PAnsiChar; stdcall; external 'bar.dll';

var
  V1: PAnsiChar;
  V2: AnsiString;
  V3, V4: DWORD;
begin
  V1 := Foo(PAnsiChar(V2), V3, V4);
  ..

关于delphi - DLL 调用在 Delphi 2010 中有效,但 AV 在 Delphi XE2 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176428/

相关文章:

Delphi TZipFile 提取零字节文件

c# - 多个应用程序域调用同一个非托管 dll

delphi - TIdHttp.Post - 无法获取 utf-8 编码

delphi - 空函数 - 占位符?

c# - Tlbimp 无法生成互操作 Dll

c - DLL 隐式链接

delphi - 简单的 OpenGL 代码不起作用

delphi - 是否可以声明长度受限且不从 0/1 开始的字符串类型?

delphi - 如何使用 DUnit 测试私有(private)方法?

c - 在c源代码中使用dll的效率