tags:

views:

252

answers:

2

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 }
+4  A: 

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.

Andreas Rejbrand
+13  A: 

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.

Mason Wheeler
Yes, and it did work in D7 because for AnsiStrings, one character is one byte.
Andreas Rejbrand