Converting UnicodeString to PAnsiChar in Delphi XE

Posted by moodforaday on Stack Overflow See other posts from Stack Overflow or by moodforaday
Published on 2010-12-28T01:32:38Z Indexed on 2010/12/28 1:54 UTC
Read the original article Hit count: 357

In Delphi XE I am using the BASS audio library, which contains this function:

function BASS_StreamCreateURL(url: PAnsiChar; offset: DWORD; flags: DWORD; 
    proc: DOWNLOADPROC; user: Pointer):HSTREAM; stdcall; external bassdll;

The 'url' parameter is of type PAnsiChar, so in my code I do a cast:

FStreamHandle := BASS_StreamCreateURL(PAnsiChar( url ) [...]

The compiler emits a warning on this line: "suspicious typecast of string to PAnsiChar". In trying to eliminate the warning, I found that the recommended way is to use a double cast:

FStreamHandle := BASS_StreamCreateURL(PAnsiChar( AnsiString( url )) [...]

This does eliminate the warning, but the BASS function now returns error code 2 ("cannot open file"), which tells me the URL string it receives is somehow broken. I cannot see what the bass DLL actually receives, but using a breakpoint in the debugger the string looks good:

var
  s : PAnsiChar;
begin
  s := PAnsiChar( AnsiString( url ));

At this point string s appears fine, but the BASS function fails when I pass it. My initial code: PAnsiChar( url ) works well with BASS, but emits a warning.

So what's the correct way of getting from UnicodeString to PAnsiChar without a warning?

© Stack Overflow or respective owner

Related posts about delphi

Related posts about pointers