Welcome to the new DelphiDabbler Code Library Documentation.

This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.

Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.

CreateBlock class method

Project: Environment Variables Unit

Unit: PJEnvVars

Class: TPJEnvironmentVars

Applies to: ~>3.0

class function CreateBlock(const NewEnv: TStrings;
  const IncludeCurrent: Boolean; const Buffer: Pointer;
  const BufSize: Integer): Integer;

Description

Creates a new custom environment block in a form suitable for passing to another process.

Parameters:

Returns:

The format of the environment block created with this method is a concatentation of the environment variables where each one is represented in Name=Value format, separated by a zero character (i.e. #0 or Char(0)) with the whole block terminated by a pair of zero characters. An example block with three variables is Foo=Lorem#0Bar=Ipsum#0Raboof=Dolore#0#0

Important. Because CreateBlock deals with buffer sizes in characters, not bytes, you must multiply the returned value by SizeOf(Char) when allocating suitable buffers with GetMem. Alternatively, use a routine such as StrAlloc that automatically takes account of the character size.

The usual way to use CreateBlock is to call it once with a nil buffer to get the required buffer size in characters, allocate the buffer and then call CreateBlock again, this time passing the actual buffer and its size, for example:

var
  EnvBlock: Pointer;
  BlockSize: Integer;
  NewEnv: TStringList;
begin
  // Create and populate NewEnv
  // ...
  // Create the environment block: include NewEnv and process' own block
  BlockSize := TPJEnvironmentVars.CreateBlock(NewEnv, True, nil, 0);
  // BlockSize is in Characters, not bytes: so needs converting to bytes
  GetMem(EnvBlock, BlockSize * SizeOf(Char));
  try
    CreateEnvBlock(NewEnv, True, EnvBlock, BlockSize);
    // Execute a program with environment block
    // ...
  finally
    FreeMem(EnvBlock);
  end;
end;