How to pass a nil in place of a const record?
Asked Answered
M

1

7

I am trying to call the WIC (Windows Imaging Component) factory method CreateEncoder:

HRESULT CreateEncoder(
  [in]            REFGUID guidContainerFormat,
  [in, optional]  const GUID *pguidVendor,
  [out, retval]   IWICBitmapEncoder **ppIEncoder
);

The general idea would be:

var
   encoder: IWICBitmapEncoder;

CreateEncoder(
      GUID_ContainerFormatIco,  //The GUID for the desired container format
      nil, //No preferred codec vendor
      {out}encoder);

For the second parameter, i want to pass nil; to indicate that i have no encoder preference

But Delphi's translation of the WinCodec.pas is:

function CreateEncoder(const guidContainerFormat: TGuid; const pguidVendor: TGUID;
      out ppIEncoder: IWICBitmapEncoder): HRESULT; stdcall;          

You'll notice that the second parameter, the optional TGUID, is declared as const.

So how do i pass it nil?

How can i pass a nil where a const record is required?

I tried the naïve solution:

const
   NULL_GUID: TGUID = ();

factory.CreateEncoder(GUID_ContainerFormatIco, NULL_GUID, {out}encoder);

and while that happens to not fail, it isn't really following the correct rules. It's passing a non-NULL address, that points to a GUID that the API doesn't know about.

I tried the naïve solution:

factory.CreateEncoder(GUID_ContainerFormatIco, TGUID(nil), {out}encoder);

but that's an Invalid typecast.

Moneyed answered 31/5, 2014 at 1:23 Comment(2)
TGUID(nil^) might also workLegitimatize
@DavidHeffernan: +1 That's usually the point when people start to look strange at you. BTDT.Unpin
B
10

You can use something like this:

const
  NULL_PGUID: PGUID = nil;
begin
  factory.CreateEncoder(GUID_ContainerFormatIco, NULL_PGUID^, {out}encoder);
end;

Or as Sertac suggested, the shorter and sweeter version:

factory.CreateEncoder(GUID_ContainerFormatIco, PGUID(nil)^, {out}encoder);

I did a test and David's suggestion of:

factory.CreateEncoder(GUID_ContainerFormatIco, TGUID(nil^), {out}encoder);    

Also works.

Blida answered 31/5, 2014 at 1:35 Comment(3)
or PGuid(nil)^ to save a variableGilman
Those are much better than the TGUID(PGUID(nil)^) things that i was fiddling with!Moneyed
Ian, your TGUID(PGUID(nil)^) was a good attempt! You could just omit that TGUID typecast since PGUID()^ already dereferences a value of TGUID so that typecast was useless there. PGUID(nil)^ can be read as that you're dereferencing a TGUID pointer to the nil pointer constant. TGUID(nil^) as that you're dereferencing nil pointer constant and that value you typecast to the TGUID type.Cusick

© 2022 - 2024 — McMap. All rights reserved.