Delphi – AOP support in Delphi

aopdelphi

Is it possible to do Aspect Oriented Programming in Delphi? I would be interested in native support as well as third party solutions.

I don't have a specific problem I want to solve with AOP, but am simply interested in studying AOP.

Best Answer

AOP depends on two things:

  • The ability to inject additional code into an existing unit of code
  • A mechanism to place conditions on where code should be injected.

This is commonly referred to as code weaving. It is a specialization within the larger study of program transformation.

JIT compiled languages have more options for implementing code weaving than statically compiled programs because more information is retained in the bytecode/IL. They also support reflection, which offers the ability to manipulate code at runtime.

Delphi.NET and Prism have the same access to these capabilities as any other .NET language.

There are two AOP frameworks for Delphi Win32 that I'm aware of. The first is MeAOP, which has already been mentioned. The second is Infra. Both projects take a similar approach to AOP. They use a combination of RTTI and clever pointer manipulation to intercept method calls so you can run additional code before or after the method call. You define your cross-cutting feature as a subclass of the framework's AOP class. You register the methods you want intercepted by passing the method name as a string argument to the AOP framework.

Both frameworks are still actively developed and are actually larger in scope than just AOP. Unfortunately documentation is somewhat sparse (and in Infra's case mostly in Portuguese)

Another project attempted AOP through source code weaving back in 2004 with some success. Basically they built an aspect weaver on top of a general purpose program transformation tool called DMS and used it to inject code into delphi source files prior to compilation. Their aspect oriented language was primarily influenced by AspectJ.

http://www.gray-area.org/Research/GenAWeave/ has links to the original paper and presentation as well as some videos of the transformation process.

It may also be possible to use runtime code instrumentation to accomplish this as well. Its a technique used by some profilers to inject counters and stack traces into running code without modifying the original source. A similar technique could be used to inject crosscutting concerns into a statically compiled executable. The PinTool project is a good example of this.

Related Topic