Search code examples
delphidelphi-xe8

Pointer typecasting in Delphi


How can I correctly typecast to a structure in Delphi? This does not work exactly like in C++ where one would just pass a &Data according to the MSDN documentation.

program Project1;

uses
  System.SysUtils,
  Winapi.Windows,
  Winapi.Winsock2;

function WSAStartup(wVersionRequired: WORD; out lpWSAData: LPWSADATA): Integer; WINAPI; external 'ws2_32.dll';

var
  Data: WSADATA;
begin
  WSAStartup(WINSOCK_VERSION, LPWSADATA(@Data)); // E2197 Constant object cannot be passed as var parameter
  ReadLn;
end.

Solution

  • I guess that you've translated the function from the MSDN documentation which reads:

    int WSAStartup(
      _In_  WORD      wVersionRequested,
      _Out_ LPWSADATA lpWSAData
    );
    

    The confusion stems from the use of the _Out_ annotation. That is a macro that expands to nothing. It is used to convey intent to tools that, for instance, convert the header file declaration to different languages. More information can be found here:

    You've erroneously translated _Out_ to the Delphi out keyword. You could simply remove that keyword and your declaration would be correct:

    function WSAStartup(wVersionRequired: WORD; lpWSAData: LPWSADATA): Integer; 
      WINAPI; external 'ws2_32.dll';
    

    Then your call would be:

    WSAStartup(WINSOCK_VERSION, @Data);
    

    Alternatively, since this parameter is not optional, you could translate it like this:

    function WSAStartup(wVersionRequired: WORD; out lpWSAData: WSADATA): Integer; 
      WINAPI; external 'ws2_32.dll';
    

    You would then call like this:

    WSAStartup(WINSOCK_VERSION, Data);
    

    You should however, use the declaration of the function that can be found in Winapi.Winsock2 and so avoid risking making such mistakes. That is, assuming that Embarcadero have not made mistakes in translation, which does sometimes happen.

    Finally, it would be remiss of me were I not to chide you, at least mildly, for ignoring the return value of the function call.