[fpc-pascal] Effective memory allocation

Constantine Yannakopoulos alfasud.ti at gmail.com
Sun Nov 2 20:49:56 CET 2014


On Sun, Nov 2, 2014 at 3:54 PM, Xiangrong Fang <xrfang at gmail.com> wrote:

> Also, I usually use pointer to pass block of memory to functions.  How do
> I implement a function with the following signature:
>
> procedure MyProc(var Buf; Len: Integer):
>
> I mean, how to handle "var Buf" inside the procedure body?
>

Use "@Buf" to get a pointer to the address of the untyped variable. If you
want to cast that variable to an internal "known" type and the compiler
complains you can always use a pointer cast: PMyKnownType(@Buf)^. You can
also use pointer arithmetic (e.g. (PElementType(@Buf) + n)^) if the
variable is known to be an array.

In Delphi (and probably FPC) it is allowed to pass a nil pointer to an
untyped variable if you need to:

begin
  MyProc(nil^, 0);
end;

The compiler understands what you are trying to do and does not complain
about the blatant nil dereference. So "var Buf;" is functionally equivalent
to "Buf: Pointer;". OTOH "const Buf;" is slightly different in the sense
that the compiler will not let you pass the untyped variable to another
routine that may change its value.

--
Constantine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20141102/a4ad1d53/attachment.html>


More information about the fpc-pascal mailing list