Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code fail in D2010, but not D7?

Tags:

delphi

Why does this code get an access error on the Result := Buffer line in D2010, but not D7?

Something, I'd guess, involving UniCode, but the compiler doesn't generate any warnings.

Any suggestions on an elegant workaround?

Edit: Ouch: the GetTempPath call is trashing the stack as evidenced by the fact that Extension is empty after the GetTempPath line, but not before... Yikes.

    function GetTempPathAndFileName( const Extension: string):  string;
    var
      Buffer: array[0..MAX_PATH] of Char;
    begin
      repeat
        GetTempPath(SizeOf(Buffer) - 1, Buffer);
        GetTempFileName(Buffer, '~', 0, Buffer);
        Result := Buffer;    // <--- crashes on this line,
        Result := ChangeFileExt(Result, Extension);
      until not FileExists(Result);
    end; { GetTempPathAndFileName }
like image 216
RobertFrank Avatar asked May 06 '10 23:05

RobertFrank


2 Answers

GetTempPath is expecting the number of chars in the buffer for its first argument, not the size in bytes. Change SizeOf to Length and it will work.

like image 96
Mason Wheeler Avatar answered Nov 15 '22 06:11

Mason Wheeler


To make it work as in D7, replace "string" with "AnsiString" and "Char" with "AnsiChar". Also, call GetTempPathA and GetTempFileNameA rather than GetTempPath and GetTempFileName.

But the approach given by Mason is probably better, for it will support Unicode file names.

like image 41
Andreas Rejbrand Avatar answered Nov 15 '22 06:11

Andreas Rejbrand