The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,862 other subscribers

Archive for the ‘Delphi’ Category

It pays to closely look to your coding

Posted by jpluimers on 2020/12/31

I like questions like [WayBack] How to check if parent menu item has “checked” child item? – VCL – Delphi-PRAXiS [en]

It means that the asker is closely looking at her or his coding.

This is important, as it helps to get your programming idioms consistent.

The code started out as:

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  i: integer;
begin
  Result := False;
  for i := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[i].Checked then
      Exit(True);
end;

and finally ended up as:

function HasCheckedSubItems(AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
      Exit(True);
  Exit(False); 
end;

Which is close to what I’d use, no matter the Delphi version:

function HasCheckedSubItems(const AMenuItem: TMenuItem): Boolean;
var
  I: integer;
begin
  for I := 0 to AMenuItem.Count - 1 do
    if AMenuItem.Items[I].Checked then
    begin
      Result := True;
      Exit;
    end;
  Result := False;
end;

My argumentation for the last form is that assignment and jumps are too conceptually different to combine in one statement.

The second form moves just one assignment, which on the current scale of nanosecond execution might not sound much, but conceptually limits the assignment to once per function call.

If you are interested in more thoughts on this topic,

  1. read How to Design Early Returns in C++ (Based on Procedural Programming) – Fluent C++
  2. watch Procedural Programming: It’s Back? It Never Went Away – Kevlin Henney [ACCU 2018] – YouTube
  3. save the slides from [WayBack

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

A garbage collector for C and C++ (and a wrapper for Delphi): The Boehm-Demers-Weiser conservative C/C++ Garbage Collector

Posted by jpluimers on 2020/12/30

I bumped into [WayBackA garbage collector for C and C++ a while ago, for which the source is at [WayBack] GitHub – ivmai/bdwgc: The Boehm-Demers-Weiser conservative C/C++ Garbage Collector (libgc, bdwgc, boehm-gc).

There is a (very old!) wrapper for Delphi too: [WayBack] 21646 API for Boehm Garbage Collector DLL

Barry Kelly <barry_j_kelly@hotmail.com>,
19 April 2004
——————————————————
This archive contains a simple API unit for the Boehm Garbage Collector DLL, along with another unit which makes it easier to use with classes, and a demonstration application. Also included is the Boehm GC DLL binary, along with source code in the gc_dll_src directory.

The files:

BoehmGc.pas
———–
This unit exports a dozen or so routines from the Boehm GC dll. Since the GC integrates with and replaces the Delphi default memory manager, you probably don’t need to use this unit unless you want to fine-tune the behaviour of the DLL. The DLL exports more routines than are in this unit; the C prototypes are in the gc_dll_src/gc.h header file, and can be imported as needed. If you allocate large chunks of memory (>100K) which don’t contain references to other chunks (and thus don’t need to be scanned for pointers), there are routines in this unit which you can use to increase performance.

General advice: don’t tweak until you need to tweak.

Gc.pas
——
This is the main unit. Put this unit first in the uses clause of you project and the project will automatically use garbage collection. If you want to use objects which require finalization and you don’t want to have to call TObject.Free / TObject.Destroy on them manually, you can use the MarkForFinalization(TObject) function. The basic pattern is to register the object for finalization in its constructor and unregister it with UnmarkForFinalization in its destructor. This handles the two most common use cases for finalization: GC-invoked finalization and manual finalization. Note that it’s always safe to behave as if GC doesn’t exist, and use GetMem/FreeMem, New/Dispose, Create/Free etc. The use of these units simply allows you to also program with garbage collection.

GcTest.dpr & GcTest.exe
———————–
This program contains simple sample code demonstrating the garbage collector in action.

BoehmGC.dll
———–
This contains the implementation of the garbage collector itself. The DLL can be recompiled from the source in gc_dll_src with various options, including multithreaded support, different pointer alignment granularities, etc.

****
The original Boehm GC source comes from: http://www.hpl.hp.com/personal/Hans_Boehm/gc/

I’m Barry Kelly: barry_j_kelly@hotmail.com

You can do anything you like with my source code (*.pas, *.dpr).

See the file gc_dll_src/LICENSEa for permissions for the GC itself.

</barry_j_kelly@hotmail.com>

Although when trying to download, I got this for both cc.embarcadero.com/Download.aspx?id=21646 and cc.embarcadero.com/Download.aspx?id=21646&prot=ftp:

Access to the path ‘\\etnaedndb02.embarcadero.com\f\webcache\cc\2004\4\19\21646.zip’ is denied.

An error has occurred while processing the page.

Please try to refresh the page, or return to the home page.

: ETNACDC04

and [WayBackJeroen Pluimers auf Twitter: “It looks like the @EmbarcaderoTech code central file cc.embarcadero.com/Item/21646 is broken: “Access to the path ‘\https://t.co/3f3blXN9mp\f\webcache\cc\2004\4\19\https://t.co/0UJUtWvxVV’ is denied.” when exploring or downloading.…”

 Explore the files in this upload

File Exploration is Disabled

We’re sorry, but errors in the uploaded zip file prevent it from being explored.

The error generated by the Zip attachment is:

Access to the path ‘\\etnaedndb02.embarcadero.com\f\webcache\cc\2004\4\19\21646.zip’ is denied.You may still be able to repair the zip file contents if you download the entire zip locally. You may also want to ask the author to repost the attachment.

Via [WayBack] delphi – Reference-counting for objects – Stack Overflow which also points to:

Downloads of stable versions: [WayBack] Download · ivmai/bdwgc Wiki · GitHub

–jeroen

Read the rest of this entry »

Posted in C, C++, Delphi, Development, Software Development | Leave a Comment »

Delphi processing all Windows messages

Posted by jpluimers on 2020/12/30

Since I had captures messages inside the main message loop, I forgot it is straightforward: create a [WayBackTApplicationEvents instance, then use the [WayBackOnMessage event and hook it to a method like

procedure TMainForm.ApplicationEventsMessage(var Msg: TMsg; var Handled: Boolean);
begin
  // figure out if the TMsg should be handled; set Handled to True if you do not want it to be processed by your application any further
  // if you do not handle it: bail out as quickly as possible
  // for performance reasons, it might be wise to have only the decision in this method, and all actual handling (including any managed variables) inside another method.
end;

Capturing these messages is limited to the ones processed through the main message loop (or message pump): these are the asynchronous ones either put there by PostMessage or related functions (like PostQuitMessage), or generated by Windows.

This means you will not see any synchronous messages sent to specific Windows using SendMessage.

Unlike the documentation for the OnMessage event, the type inside the method is TMsg from the unit  [WayBack]WinApi.Windows, which is an alias for the (documentation mentioned) tagMSG in the same unit; neither type is documented at docs.embarcadero.com or docwiki.embarcadero.com. Luckily, it is documented in the Windows SDK as the structure [WayBacktagMSG.

That structure is not the same as the [WayBackTMessage type inside the unit WinApi.Messages [WayBack], as TMessage omits these fields from TMsg:

  • HWND hwnd;
  • DWORD time;
  • POINT pt;
  • DWORD lPrivate;

Luckily the [WayBack] TMessageEvent (that describes the type of the signature of the event method) is better in this regard:

TMessageEvent = procedure (var Msg: TMsg; var Handled: Boolean) of object;

TMessageEvent includes the following parameters:

  • Msg identifies the Windows message that triggered the event.
  • Handled indicates whether the event handler responded to the message. If the event handler sets Handled to True, the application assumes that the message has been completely handled and halts any subsequent processing of the message.

TApplicationEvents is actually a multi-cast component (one of the very few multi-casting things parts of the Delphi VCL): an undocumented TMultiCaster class inside the unit Vcl.AppEvnts [WayBack].

A bit reminder though: ALL queued (not sent!) Windows messages flow through this method, so make it as short and efficient as possible, so from the OnMessage documentation:

OnMessage only receives messages that are posted to the message queue, not those sent directly with the Windows API SendMessage function.

Warning: Caution:Thousands of messages per second flow though this event. Be careful when coding the handler, because it can affect the performance of the entire application.
Tip: Call the CancelDispatch method from an OnMessage event handler to prevent the application from forwarding the event to any other application events objects.
It took until Delphi 2010 for the method [Archive.isTCustomApplicationEvents.CancelDispatch to be documented:
Prevents other TCustomApplicationEvents objects from receiving the current event.

A few more relevant links if you want to also hook SendMessage based messages:

Read the rest of this entry »

Posted in Conference Topics, Conferences, Delphi, Development, Event, Software Development | Leave a Comment »

Why does my Android application, compiled with development tool XXX version YYY, no longer work?

Posted by jpluimers on 2020/12/29

Still relevant, not limited to Delphi, though other environments often have a better warning system in place: [WayBack] Why does my Android application, compiled with Delphi Rio, no longer work?.

TL;DR: over time, Android and the development tools for it, require you to support more recent Android SDK levels.

Those SDK levels come with different requirements than past ones, so when recompiling, you need to check if you fulfill these requirements.

When you don’t, the application is likely to crash, sometimes without any indication why.

Via: [WayBack] Dalija Prasnikar – Google+ /

[WayBack] Dalija Prasnikar on Twitter: “Why does my Android application, compiled with Delphi Rio, no longer work?”

–jeroen

Posted in Android, Delphi, Development, Mobile Development, Software Development | Leave a Comment »

Small Delphi tricks: initialise out parameters in the caller when they are stored in local variables; a Run for TProc

Posted by jpluimers on 2020/12/29

Two small Delphi tricks:

On out parameters

When you have out parameters, and the caller passes local variables for them, remember that:

  1. the compiler then will not issue an “unitialised variable” warning any more because it expects the callee to fill that parameter
  2. if the local variable is non-managed, it will have a random value depending on the call stack state

A RunProc method that executes a TProc

Every so often you want to refactor a method to use two or more different algorithm implementations.

A good start is to have some conditional, to choose the algorithm, then have anonymous methods implement each algorithm.

This quickly gives you a feel of where the local vars of the original method need to go:

  • local to an implementation
  • local to the original method
  • parameters to the algorithm

A parameterless runner can be a good start to call these methods:

uses
   System.SysUtils;
/...
procedure RunProc(const AProc: TProc);
begin
  AProc();
end;

You can extend this to TProc<T> and further generic forms, by adding parameters. In that case however, the need to be inside a record (because global methods cannot be generic).

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

Is this code safe? function Some(const Str : AnsiString); var arr : TBytes …

Posted by jpluimers on 2020/12/24

[WayBack] Is this code safe? function Some(const Str : AnsiString); var arr : TBytes absolute Str; begin fSomeMethodWithTBytesParam(arr); <- arr is properly c… – Jacek Laskowski – Google+

Such a seemingly simple question:

Is this code safe?

procedure Some(const Str : AnsiString); 
var arr : TBytes absolute Str; 
begin
  fSomeMethodWithTBytesParam(arr); // <- arr is properly casted to string bytes? 
end;

Such a wealth of information in the comments:

  • No it is not, except for the nil-pointer case
  • The compiler has for instance an implicit length prefix
  • In 32-bit mode, the Length prefix of strings and dynamic arrays are both 32-bits
  • In 64-bit mode, the Length prefix of strings is 32-bits, but the one for dynamic arrays is 64-bits
  • use BytesOf to transform from characters to bytes
  • do not store binary data into strings of single-byte character sets

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

PlasticSCM memories

Posted by jpluimers on 2020/12/23

Spending most of your career as an independent contractor, you bump into a lot of toolchains.

Part of those toolchains usually involved (and by now surely should involve) version control for both development and infrastructure configuration management.

I remember PlasticSCM quite well.

The really good part is the branch overview (called Branch Explorer) in the PlasticSCM UI, as it is:

They also have frequent updates, which however are hard to discover because there is no built-in update mechanism that notifies you of them.

Those updates are badly needed, because I kept bumping into bugs. Which is odd, because I bumped into far less issues when using UI layers for SVN, TFS, Mercurial and git (SourceTree being a major exception, but they seem to have recovered from a long period of bad versions a few years back).

So here are some of my gripes, that might have been fixed by now.

Read the rest of this entry »

Posted in Delphi, Development, PlasticSCM, Software Development, Source Code Management, Versioning | Leave a Comment »

How to debug Delphi JSON export stack-overflows: watch the fields and their circular references

Posted by jpluimers on 2020/12/23

Unlike Delphi RTL XML support which is property based, the JSON support is field based.

By default, JSON uses all fields (no matter their protection level, so anything from strict private to published  is taken into account).

When there are cycles, they are not detected: it will just stack-overflow with a high set of entries like this:

REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.MarshalSimpleField($788BFB40,$78AB0150)
REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.MarshalData($78AB0150)
REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.MarshalValue((($A9B7E8, Pointer($AFE168) as IValueData, 80, 336, 2024472912, $78AB0150, TClass($78AB0150), 80, 336, 2024472912, 2,77471682335019e+34, 1,00022251675539e-314, 0,00000000737961e-4933, 2024472912, 202447,2912, 2024472912, 2024472912, ($78AB0150, nil), $78AB0150)),???)
REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.MarshalSimpleField($78A921D0,$78AA69C0)
REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.MarshalData($78AA69C0)
REST.JsonReflect.{REST.JsonReflect}TTypeMarshaller.Marshal(???)

The easiest way to debug this is to:

  1. Set breakpoints in procedure TTypeMarshaller<TSerial>.MarshalData(Data: TObject);
    1. First breakpoint on the for rttiField loop
      • Watch or log these values (the first two usually are the same, the last two too):
        1. ComposeTypeName(Data) which gives you the fully qualified name (including unit and class) of the type exposing the fields
        2. Data.ClassName as a sanity check
        3. rttiType.Name which should be the same as Data.ClassName
    2. Second breakpoint inside the for rttiField loop on the if not ShouldMarshalstatement
      • Watch or log these values:
        1. rttiType.Name inside the loop, it changes value to match rttiField.Name, because of a debugger bug not showing it as E2171 Variable 'rttiType' inaccessible here due to optimization.
        2. rttiField.Name the actual field name

Tricks to circumvent circular references:

  • remember that fields with a reference to function value are not marshaled, so they are an excellent way of shoehorning in a dependency in (the reference value will be a capture which includes the instance data of the function to be called)
  • applying a [JsonMarshalled(False)] attribute (be sure to use unit REST.Json.Types!) only works when used inside non-generic types:
    • a class like TMySoapHeaderValue<T: IInterface> = class will not expose these attributes
    • a class like TMySoapHeaderValue = class will expose these attributes

You can check the JsonMarshalled problem by setting a breakpoint inside function LazyLoadAttributes(var P: PByte): TFunc<TArray<TCustomAttribute>>; on the line Exit(nil); and watch the value for Handle^.

Posted in Conference Topics, Conferences, Delphi, Development, Event, Software Development | Leave a Comment »

If you control both caller and callee: do not “override” functions by introducing a function with the same name

Posted by jpluimers on 2020/12/22

Every now and then I see people “overriding” a function by introducing a function with the same name.

Often this raises a lot of confusion, because the override will only work if you have the unit of the override closer in your user scope.

Example:

Unit AdoOverrideUnit;

interface

function VarTypeToDataType(VarType: Integer): TFieldType;

implementation

uses
  Data.DB;

function VarTypeToDataType(VarType: Integer): TFieldType;
begin
  Result := Data.DB.VarTypeToDataType(VarType);
  // override Result for some ADO specific data management layer case.
  // ...
end;

end.

In this case it is much better to call the override AdoVarTypeToDataType instead of VarTypeToDataType.

Otherwise, when AdoOverrideUnit is not closer in scope than Data.DB, the wrong method will be called which is hard to track down.

–jeroen

Posted in Delphi, Development, Software Development | Leave a Comment »

List Of Windows Messages – WineHQ Wiki

Posted by jpluimers on 2020/12/17

Easiest way to find which message # (decimal or hexadecimal) belongs to which message and vice versa:

None of the lists are completely accurate, but they get you going.

For comparison: an early Windows 10 SDK WinUser.h and [Archive.is] NativeMethods.cs

Translations:

–jeroen

Posted in C, C++, Delphi, Development, Software Development | Leave a Comment »