如何将字符串变量传递给期望PChar的函数?

use*_*060 7 delphi string pchar

我有这个代码:

ShellExecute(Handle, 'open',
             'C:\Users\user\Desktop\sample\menu\WTSHELP\start.html',
             nil, nil, sw_Show);
Run Code Online (Sandbox Code Playgroud)

如何用字符串变量替换第三个参数中的文字?如果我使用下面的代码,它不会编译.

var
  dir: string;

dir := 'C:\Users\user\Desktop\sample\menu\WTSHELP\start.html';
ShellExecute(Handle, 'open', dir, nil, nil, sw_Show);
Run Code Online (Sandbox Code Playgroud)

And*_*and 9

我认为这dir是类型string.然后

ShellExecute(Handle, 'open', PChar(dir), nil, nil, SW_SHOWNORMAL);
Run Code Online (Sandbox Code Playgroud)

应该管用.的确,编译器告诉你这个; 它说的像

[DCC Error] Unit1.pas(27): E2010 Incompatible types: 'string' and 'PWideChar'
Run Code Online (Sandbox Code Playgroud)

(另请注意,通常SW_SHOWNORMAL在打电话时使用ShellExecute.)

  • @SebastianGodelet:不,这正是你为什么不要*使用`PWideChar`的原因.在Delphi> = 2009中,`PChar`意味着'PWideChar`.因此,使用Delphi 2010的OP将获得上述错误消息,并且原则上可以使用这两个选项中的任何一个.但是如果你使用Delphi <2009,那么``Windows.pas`中定义的`ShellExecute`将引用`Shell32.dll`中的`ShellExecuteA`,因此它会期望非Unicode的`PChar`(即`PAnsiChar `).因此,在*两个*情况下,`PChar`都有效.如果使用`PWideChar`,它只能在Delphi> = 2009中使用. (5认同)

Nic*_*ges 6

ShellExecute是一个Windows API.因此,您需要将PChar类型传递给它.

如果我正确地假设您的dir变量是一个字符串,那么您可以将该字符串转换为PChar,并调用ShellExecute如下:

ShellExecute(Handle,'open', PChar(dir) ,nil,nil,sw_Show);
Run Code Online (Sandbox Code Playgroud)