Search code examples
delphidelphi-10.1-berlin

Converting C headers to Delphi - Opaque Data Type


During the conversion process I come across the following C code:

/** Opaque data type for the error object.
*/
typedef struct kError * KErrorRef;

Where is kError declared?

The conversion tool provided by Rudy Velthuis produces this code:

type
  {$EXTERNALSYM KErrorRef}
  KErrorRef = ^kError;

When I try to compile it, I get this error message:

[dcc32 Error] ukError.pas(50): E2003 Undeclared identifier: 'kError'

What is the appropriate way of converting the C code?


Solution

  • Where is kError declared?

    Nowhere, because it is not actually needed.

    In this declaration:

    typedef struct kError * KErrorRef;
    

    struct kError is an incomplete type, which is allowed when used with a pointer.

    The declaration is roughly equivalent to this:

    // forward declaration of some as-yet unknown struct type
    struct kError;
    
    // this is OK; compiler knows the size of a pointer, which is not
    // affected by the size of the actual struct being pointed to
    typedef kError *KErrorRef;
    

    The conversion tool provided by Rudy Velthuis produces this code

    The tool is not producing the correct Delphi code in this instance. When dealing with a typedef for an incomplete (forward-declared) struct type, it should produce Delphi code more like this instead, if the actual struct type is not declared later on:

    type
      {$EXTERNALSYM KErrorRef}
      KErrorRef = ^kError;
      {$NODEFINE kError}
      kError = record
      end;