Interfaces as parameters: why const? lazarus / 21-General ---------------------------------------------------------------------- ArminLinder · 2023-09-05 23:19 Hi all, I spent considerable time to fix a progam which ran into SIGSEV. Finally, and with some stabbing in the dark I was able to resolve it: if I pass an interface as a paramter, meaning I can pass any object which implements the interface, I need to use the const keyword. Simple question: why? This is the demo code (Application type: simple) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; type   { INoiseInterface }   INoiseInterface = interface(IInterface)    procedure MakeNoise;  end;   { TCar }   TCar = class(TInterfacedObject, INoiseInterface)   public    procedure MakeNoise;  end;   { TCat }   TCat = class(TInterfacedObject, INoiseInterface)   public    procedure MakeNoise;  end;   { TCat }   procedure TCat.MakeNoise;  begin    Writeln('Meow!');  end;    { TCar }   procedure TCar.MakeNoise;  begin    Writeln('Sound Horn');  end;   // procedure TestMakeNoise(const aNoiseMaker: INoiseInterface);   // this works  procedure TestMakeNoise(aNoiseMaker: INoiseInterface);              // this crashes   begin    aNoiseMaker.MakeNoise;  end; var  aCar: TCar;  aCat: TCat; begin  aCar := TCar.Create;  TestMakeNoise(aCar);  aCar.Destroy;  aCat := TCat.Create;  TestMakeNoise(aCat);  aCat.Destroy;  Readln;end. If I use the commented out code, everything works. If I don't, the program crashes with SIGSEV when the object is destroyed. FPC 3.2.2 on Windows 10 Thanks, Armin. ---------------------------------------------------------------------- Remy Lebeau · 2023-09-05 23:50 Quote from: ArminLinder on September 06, 2023, 01:19:09 amif I pass an interface as a paramter, meaning I can pass any object which implements the interface, I need to use the const keyword. Simple question: why? 2 words - reference counting!  You are mixing object references and interface references, which is always a recipe for disaster. When you pass an interface to your function WITHOUT the const, the interface's refcount gets incremented upon entry into the function, then decremented upon exit of the function. You are creating interfaced objects with no interface references to them, so the objects have an initial refcount of 0. The refcount increments to 1 and then decrements to 0, destroying the object. Then you try to destroy the object manually afterwards, which crashes: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TestMakeNoise(aNoiseMaker: INoiseInterface);begin // refcount + 1   aNoiseMaker.MakeNoise;end; // refcount - 1     var  aCar: TCar;  aCat: TCat;begin  aCar := TCar.Create; // refcount 0  TestMakeNoise(aCar); // refcount 1-then-0, aCar destroyed!  aCar.Destroy; // invalid object here!   aCat := TCat.Create; // refcount 0  TestMakeNoise(aCat); // refcount 1-then-0, aCat destroyed!  aCat.Destroy; // invalid object here!   Readln;end.  When you pass an interface to the function WITH the const, the interface's refcount IS NOT touched at all, allowing you to safely destroy the object manually after the function exits: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TestMakeNoise(const aNoiseMaker: INoiseInterface);begin // refcount untouched!  aNoiseMaker.MakeNoise;end; // refcount untouched!     var  aCar: TCar;  aCat: TCat;begin  aCar := TCar.Create; // refcount 0  TestMakeNoise(aCar); // refcount remains 0  aCar.Destroy; // object is ok here!   aCat := TCat.Create; // refcount 0  TestMakeNoise(aCat); // refcount remains 0  aCat.Destroy; // object is ok here!   Readln;end.  The correct solution is to change your aCar and aCat variables to INoiseInterface instead, then it won't matter if the function touches the interface's refcount or not, since you will have your own reference to the interface outside of the function, eg: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  aCar: INoiseInterface;  aCat: INoiseInterface; begin  aCar := TCar.Create; // refcount 1  TestMakeNoise(aCar); // refcount 2-then-1, or remains the same, doesn't matter  aCar := nil; // refcount 0, aCar destroyed   aCat := TCat.Create; // refcount 1  TestMakeNoise(aCat); // refcount 2-then-1, or remains the same, doesn't matter  aCat := nil; // refcount 0, aCat destroyed   Readln;end. ---------------------------------------------------------------------- cdbc · 2023-09-06 06:25 Hi In addition to Remy's well written explanation, there's the other type of interface, namely Corba, which is not ref-counted. You can read more about them in the documentation and study the implementation of the observer pattern in "TPersistent" class. edit: Requires {$interfaces corba} and not descend from IInterface. Regards Benny ---------------------------------------------------------------------- Thaddy · 2023-09-06 06:49 Yes, but he derives from TInterfacedObject, which implements IUnknown, so is COM. The error is indeed mixing references to the class and the interface: it must be either/or. ---------------------------------------------------------------------- Warfley · 2023-09-06 07:00 Another solution is, when you create your object simply call _AddRef once, to indicate that you have one (non interface based) reference Alternatively, as mentioned above, if you just want the abstraction functionality without the refcounting simply use CORBA interfaces. ---------------------------------------------------------------------- ArminLinder · 2023-09-06 15:44 Thank you for your valuable input. I understood some of it, but not all. SO forgive me if I continue asking. CORBA/COM. I have always seen those as a means of interfacing between routines located in separate programs (COM) and between client and server (CORBA). I am surprised to see those two pup up related to passing an interface as a parameter. How do these puzzle parts fit together? Interfaces: as I got to know them (C#, the way leading out of inheritance hell, prefer composition over inheritance), they do only exist as a definition of a set of methods or properties every object being passed needs to satisfy. As I understand it, if using the interface the mechanism must increase the refcount of the underlying object, not a refcount of the interface. How can an interface have a refcount of its own at all? This design looks a bit strange to me. If I put everything together, when not using const, a refcount of the interface is increased on method entry, but the refcount of the underlying object is decreased on exit? To me, something smells fishy here. Armin. ---------------------------------------------------------------------- ArminLinder · 2023-09-06 15:55 Quote from: Remy Lebeau on September 06, 2023, 01:50:50 amThe correct solution is to change your aCar and aCat variables to INoiseInterface instead Remy, changing the variable's types does not fit my needs. I don't know how I can express this (sorry, no native English speaker), so I try to describe the problem I try to resolve using interfaces. in short: composition over inheritance. Arbitrary objects supporting a specific set of methods, which are grouped together as an "interface". Any object, which is able to fullfill the definition, can be passed. This would eliminate one of OOPs inheritance weaknesses: if I want to pass a parameter to a method, I can only pass an object of that type, or an object derived from the type. This required inheritance to be taken to absurd levels, and all objects of a domain having to be based on that dreaded "god- object". It seems to me, that the Pascal'ish definition of an interface is different? Armin. ---------------------------------------------------------------------- Warfley · 2023-09-06 16:34 Then you can simply use raw CORBA interfaces by adding "{$INTERFACES CORBA}" to the unit that defines the interfaces. This should give you the behavior you expect. See: https://lazarus- ccr.sourceforge.io/fpcdoc/ref/refse50.html ---------------------------------------------------------------------- ArminLinder · 2023-09-06 16:40 Warfly, thank you! can you talk a bit more about the interface-types and how, though used in local method calls,  they are related to interprocess- communication standards like CORBA (https://en.wikipedia.org/wiki/Comm on_Object_Request_Broker_Architecture) and COM (https://en.wikipedia.org/wiki/Component_Object_Model)? Thanks, Armin. ---------------------------------------------------------------------- ArminLinder · 2023-09-06 17:06 Once I got it, I would also volunteer to update the wiki. I found three differend articles: Understanding Interfaces: https://wiki.freepascal.org/Understanding_Interfaces How To Use Interfaces: https://wiki.freepascal.org/How_To_Use_Interfaces Interfaces: https://wiki.freepascal.org/Interfaces I wasn't able to understand any of those. Seems each one sheds a bit of light on some arbitrary aspects of using intercaces, but they all failed to giva a complete view on how interfaces are treated in Pascal. The texts are questionable too, they reference other uses of the "Interface" keyword, like Interface (unit) and interface (Widgetset), which does only contribute to the confusion. There is moreover an out-of-context statement in one article, explicitly warning of using CORBA (as I understood it) since it "LEAKS". WTF? Armin ---------------------------------------------------------------------- Warfley · 2023-09-06 21:30 Quote from: ArminLinder on September 06, 2023, 06:40:54 pmWarfly, thank you! can you talk a bit more about the interface-types and how, though used in local method calls,  they are related to interprocess- communication standards like CORBA (https://en.wikipedia.org/wiki/Comm on_Object_Request_Broker_Architecture) and COM (https://en.wikipedia.org/wiki/Component_Object_Model)? Thanks, Armin. Nah, I'm the wrong person to talk about this sort of stuff. I've never been interested enough in windows development to dive deep into COM, nor that big of a Java Enthusiast to use CORBA productively. I personally only care about the usage and capabilities within Pascal. COM interfaces are interesting because their reference counting allows for automated memory management, if you want to see a great example for this look at the GMP implementation in fpc. E.g. to simply compute (a+b)*c for GMP numbers (which are dynamic data structures) in the classical manual memory management API you would write Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  a, b, c, tmp: mpz_t;begin  // init a, b, c   mpz_init(tmp); // allocate memory for tmp  try    mpz_add(tmp, a, b); // tmp := (a + b)    mpz_mul(Result, tmp, c); // Result := tmp * c  finally    mpz_clear(tmp); // Free tmp  end;  end; While with reference counted interface it is Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  a, b, c, tmp: MPInteger; // Reference counted COM interfacesbegin  // Init a, b, c   Result := (a + b) * c;end; This is extremely useful, but also quite specific. Corba on the other hand is what you typically associate interfaces with. If you come from the typical OOP world, e.g. when implementing some UML architectures, or coming from languages like java or C#, an interface is something that only tellsyou about the methods and does not provide custom handling and special functionality. If you just want interfaces in the OOP sense, you want to use CORBA, if you want reference counting you use COM. For IPC maybe someone more knowledgeable can tell you more ---------------------------------------------------------------------- nanobit · 2023-09-07 04:10 Quote from: ArminLinder on September 06, 2023, 05:44:15 pmCORBA/COM. If you want to stay Delphi compatible, then use COM. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 08:25 Guys, I am still confused. I'll try to express why. In my world (Java, c#) an interface is not an object. It does not take any memory, it is not created, not destroyed, and therefore there is no need for reference counting. It is a "filter" letting pass only objects, which do expose a specific set of methods and properties. The main jusitifcation for their existence is to resolve issues with multiple inheritance and "inheritance hell" which does lead to the "god object" problem, tackled in OOP by the "composition over inheritance" paradigm. The use of interfaces  also gives the programmers a mechnism to "decouple" their objects. Creation and destruction of the underlying object(s) is a wholly different thing. CORBA and COM talk about a completely different thing called "interface" too: the ability of one program to talk to a routine which is part of a different program (COM), or even a different program running on a different machine (CORBA, DCOM). This requires additional mechanisms, like finding the thing (a unique name), a way to export the interface definition, restricting access, handling the underlying transport layer and it's problems and converting incompatible data formats, just to name some. To me it seems, that both approaches got, at some point, mixed up in Pascal in a very strange and disgusting way. Seen this way (which seems the natural way to see it) and though I am a big fan of Pascal, I consider Pascals behaviour to unexpectedly free an underlying object as a total blunder, a severe bug, which has, at some point, made it into the language standard. Long story short: I get myself to live with {$interfaces corba} and I stop trying to talk any sense into why it was named "CORBA". Armin Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$interfaces corba} type   { INoiseInterface }   INoiseInterface = interface    procedure MakeNoise;  end;   IMovementInterface = interface    procedure Move;  end;   { TCar }   TCar = class(INoiseInterface, IMovementInterface)   public    procedure MakeNoise;    procedure Move;  end;   { TCat }   TCat = class(INoiseInterface, IMovementInterface)   public    procedure MakeNoise;    procedure Move;  end;   TElectricalThing = class    // anything you want to know about your electrical things, like wattage, weight, size, price, recyling, whatever  end;   { TFridge }   TFridge = class(TElectricalThing, INoiseInterface, IMovementInterface)  public    procedure MakeNoise;    procedure Move;   end;   { TFridge }   procedure TFridge.MakeNoise;  begin    Writeln('Compressor humming');  end;   procedure TFridge.Move;  begin    Writeln('Sorry, cannot move');  end;   { TCat }   procedure TCat.MakeNoise;  begin    Writeln('Meow!');  end;   procedure TCat.Move;  begin    Writeln('Silky paw tapping');  end;    { TCar }   procedure TCar.MakeNoise;  begin    Writeln('Sound Horn');  end;   procedure TCar.Move;  begin    Writeln('Turn wheels');  end;   procedure TestMakeNoise(aNoiseMaker: INoiseInterface);   begin    aNoiseMaker.MakeNoise;  end;   procedure TestMoveThingy(aMovableThingy: IMovementInterface);   begin    aMovableThingy.Move;  end;  var  aCar: TCar;  aCat: TCat;  aFridge: TFridge; begin  aCar := TCar.Create;  TestMakeNoise(aCar);  TestMoveThingy(aCar);  aCar.Destroy;  aCat := TCat.Create;  TestMakeNoise(aCat);  TestMoveThingy(aCat);  aCat.Destroy;  aFridge := TFridge.Create;  TestMakeNoise(aFridge);  TestMoveThingy(aFridge);  aFridge.Destroy;  Readln;end. ---------------------------------------------------------------------- marcov · 2023-09-07 08:51 Quote from: ArminLinder on September 07, 2023, 10:25:58 amGuys, I am still confused. I'll try to express why. In my world (Java, c#) an interface is not an object. It does not take any memory, it is not created, not destroyed, and therefore there is no need for reference counting. It is a "filter" letting pass only objects, which do expose a specific set of methods and properties. The main jusitifcation for their existence is to resolve issues with multiple inheritance and "inheritance hell" which does lead to the "god object" problem, represented in OOP by the "composition over inheritance" paradigm. Creation and destruction of the underlying object(s) is a wholly different thing. The Delphi interface concept (the COM interface in Free Pascal) is roughly the same conceptually, but it does require memory, as casts/AS/IS must investigate runtime datastructures of objects using introspection. This is benign though. However Delphi _only_ introduced interfaces for COM's sake, to be able to interface objects of *foreign language* origin. As a kind of OO Level interop as it were.  Mostly to embed activex applets written in VB or connect to services written in C++ . For that purpose COM implements refcounting so that when the Pascal no longer has a reference to it, memory management can be redirected back to the foreign languages runtime. When this was introduced into FPC, there was some talk that COM didn't make sense on non windows, I was working a bit with Corba and Java, and there the refcounts were managed manually. It was proposed as a possible alternative to the COM interfaces, so the moniker CORBA stuck for non reference counted interfaces. (there is no other relation) QuoteCORBA and COM talk about a completely different thing too, also called "interface", the ability of one program to talk to a routine which is part of a different program (COM), or even a different program running on a different machine (CORBA, DCOM). This requires additional mechanisms, like finding the thing (name resolution), a way to export the interface definition, restricting access, handling the underlying transport layer and it's problems and converting incompatible data formats, just to name some. The implementation yes. From a purely conceptual language view however, it is simply a reference to a foreign object, e.g. an object that doesn't inherit from your rooted object tree and all operations are redirected to the foreign runtime. Whether managed by a broker or not. Aeons later (in fairly recent times, 2018 or so) Delphi also got a way to skip the reference counting by so called weak references. I'm not terribly versed in that. Besides all this, interfaces were introduced relatively late to Delphi, when the core of the language and libraries (VCL) already stood. The usage of them in typical Delphi code is quite low, though some people (ab)use them heavily to simulate more C#/Java behaviour and/or get some form of automated memory management. QuoteTo me it seems, that both approaches got, at some point, mixed up in Pascal in a very strange and disgusting way. The terminology is a bit strange, for sure. Disgusting is a pointless word in such discussions. QuoteSeen this way (which seems the natural way to see it) and though I am a big fan of Pascal, I consider Pascals behaviour to unexpectedly free an underlying object as a total blunder, a severe bug, which has, at some point, made it into the language standard. See above. It was primarily meant to interface _foreign_ objects. You can use native objects, but some care must be taken (first order rule of thumb: don't mix object and interface references) QuoteLong story short: I get myself to live with {$interfaces corba} and const, and I stop trying to talk any sense into it. No experience there. I never used them much. ---------------------------------------------------------------------- Warfley · 2023-09-07 08:52 Quote from: ArminLinder on September 07, 2023, 10:25:58 amIn my world (Java, c#) an interface is not an object. It does not take any memory, it is not created, not destroyed, and therefore there is no need for reference counting. It is a "filter" letting pass only objects, which do expose a specific set of methods and properties. The main jusitifcation for their existence is to resolve issues with multiple inheritance and "inheritance hell" which does lead to the "god object" problem, represented in OOP by the "composition over inheritance" paradigm. Creation and destruction of the underlying object(s) is a wholly different thing. In Java and C# an interface is a reference to an object of unknown type, but with a "promise" that it provides certain functionality. But it is an object and you can access it as an object anytime you want, case in point: Code: Java  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i interface IMain { } public class Main implements IMain {  public static void main(String[] args) {    IMain m = new Main();    Main m2 = (Main)m; // get object behind interface  }} And this is the exact same behavior that CORBA interfaces provide in Pascal. Quote from: ArminLinder on September 07, 2023, 10:25:58 amCORBA and COM talk about a completely different thing too, also called "interface", the ability of one program to talk to a routine which is part of a different program (COM), or even a different program running on a different machine (CORBA, DCOM). This requires additional mechanisms, like finding the thing (name resolution), a way to export the interface definition, restricting access, handling the underlying transport layer and it's problems and converting incompatible data formats, just to name some. But that this is exactly how it works in Java and C#. Java interfaces have also been built to be compatible with CORBA on a language level. When you create your CORBA interface definition, this will simply be transpiled to a Java language level interface to be used on a code level. And it's the same with C# and COM interfaces. C# language level interfaces are COM interfaces, like it is in Pascal (you don't notice the refcounting because C# is garbage collected). So Pascal is behaving exactly the same as C#, if you use {$Interfaces COM}. And if you want "raw interfaces" simply use CORBA Also, why should this be mutually exclusive in the first place? Look at functions. You can write functions to encapsulate your code into different chunks to get a better readable code. But you can also use functions to export within a shared library to be used within another program. With interfaces it's exactly the same. You can use interfaces as a language tool like you do with Java and C#. But if you want to be able to use objects and methods in another program, you can export them through the COM or CORBA mechanisms. It's basically the OOP version of what we are doing with functions since the ELF introduction 50 years ago. Just because functions are used in ELF to create libraries, it does not mean that we shouldn't use them to structure our program internally. Similarly, just because interfaces implement CORBA or COM, it doesn't mean we shouldn't use them internally. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 10:56 Marcov, as usual, shed a bright light on the historic reasons, which do clarify most of my issues, thanks very much. Warfly, thank you too, and I guess your input will at some point help someone who is after the COM approach, but as I already mentioned, my current focus is on using interfaces to resolve issues with inheritance in a single, monolithic program. CORBA was misleading for me, since in a different project I got in contact with programmers coding in Java and using CORBA for networking, and this set my mind to think that CORBA was a networking communications protocol library. It didn't come to my mind that it could be used for local purposes as well, or even be built into a language. For my current purposes CORBA interfaces fit best, so I'll concentrate on them. As soon as I switch to CORBA, the Const can go away, and things start to fall into place like I wanted them. Meanwhile I got all my pieces together. This is the test code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$interfaces corba} uses SysUtils; type   { INoiseInterface }   INoiseInterface = interface    procedure MakeNoise;  end;   IMovementInterface = interface ['AnyUniqueIDWillDoToSatisfySysutils.Supports']    procedure Move;  end;   { TCar }   TCar = class(INoiseInterface, IMovementInterface)   public    procedure MakeNoise;    procedure Move;  end;   { TCat }   TCat = class(INoiseInterface, IMovementInterface)   public    procedure MakeNoise;    procedure Move;  end;   TElectricalThing = class    // anything you want to know about your electrical things, like wattage, weight, size, price, recyling, whatever  end;   { TFridge }   TFridge = class(TElectricalThing, INoiseInterface)  public    procedure MakeNoise;  end;   { TFridge }   procedure TFridge.MakeNoise;  begin    Writeln('Compressor humming');  end;   { TCat }   procedure TCat.MakeNoise;  begin    Writeln('Meow!');  end;   procedure TCat.Move;  begin    Writeln('Silky paw tapping');  end;    { TCar }   procedure TCar.MakeNoise;  begin    Writeln('Sound Horn');  end;   procedure TCar.Move;  begin    Writeln('Turn wheels');  end;   procedure TestMakeNoise(aNoiseMaker: INoiseInterface);   begin    aNoiseMaker.MakeNoise;  end;   procedure TestMoveThingy(aMovableThingy: IMovementInterface);   begin    aMovableThingy.Move;  end;  var  aCar: TCar;  aCat: TCat;  aFridge: TFridge;  aNoiseSourceList: array of INoiseInterface;  aDeviceList: array of TObject;  i: INoiseInterface;  o: TObject;  MovementInterface : IMovementInterface; begin  // simple stuff first: using objects  writeln(' ------- Test 1 ------- ');  aCar := TCar.Create;  TestMakeNoise(aCar);  TestMoveThingy(aCar);  aCar.Destroy;  aCat := TCat.Create;  TestMakeNoise(aCat);  TestMoveThingy(aCat);  aCat.Destroy;  aFridge := TFridge.Create;  TestMakeNoise(aFridge);  // TestMoveThingy(aFridge);   // won't work, since a fridge cannot move  aFridge.Destroy;  writeln(' ------- Test 2 ------- ');  // a list of noise-making objects  aNoiseSourceList := [TCar.Create,TCat.Create,TFridge.Create];  for i in aNoiseSourceList do      testMakeNoise(i);  writeln(' ------- Test 3 ------- ');  // a list of arbitrary objects and a filter  aDeviceList := [TCar.Create,TCat.Create,TFridge.Create];  for o in aDeviceList do    if Supports(o,IMovementInterface,MovementInterface) then TestMoveThingy(MovementInterface);      // if o is IMovementInterface then TestMoveThingy(IMovementInterface(o));    // not possible?  Readln;end.  The only and final issue I ran into is, that I did not find a way to directly pass an arbitrary object supporting an interface to a procedure which expects the interface. See the 3rd line from the very end of the demo program. I found a kind of workaround though, using "supports" from "systutils", and an additional MovementInterface variable. Having to declare a GUID is also an unwanted and unexpected side effect, since the wiki states otherwise. Any thoughts from your side? Armin. ---------------------------------------------------------------------- Thaddy · 2023-09-07 11:24 FWIW, do not use CORBA unless you fully understand its underlying consequences. In other words: almost nobody uses it anymore. That said: IF you understand it it can be a powerful tool in the toolbox, but note my first remark and note that you will loose refcounting. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 11:45 Aargh. Thought, I had a good solution, but alas, my test program leaks memory. Well, I create objects for the list, so I need to destroy them as well. This is fairly easy for the list of objects (aDeviceList), but I failed to do it for the list of interfaces. How do I need to free the objects contained in aNoiseSourceList? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   writeln(' ------- Test 2 ------- ');  // a list of noise-making objects  aNoiseSourceList := [TCar.Create,TCat.Create,TFridge.Create];  for i in aNoiseSourceList do      testMakeNoise(i);  // cannot destroy, won't compile --> memory leak  // for i in aNoiseSourceList do  //    i.Destroy;  writeln(' ------- Test 3 ------- ');  // a list of arbitrary objects and a filter  aDeviceList := [TCar.Create,TCat.Create,TFridge.Create];  for o in aDeviceList do    if Supports(o,IMovementInterface,MovementInterface) then TestMoveThingy(MovementInterface);  // what I create, I need to destroy.  for o in aDeviceList do     o.Destroy;  Readln; Another welcome consequence: I do not need a GUID for the Interface definition any more. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   IMovementInterface = interface    procedure Move;  end; @Thaddy: what are those consequences? ---------------------------------------------------------------------- Thaddy · 2023-09-07 11:51 If you used COM and derive from TInterfacedobject and you instantiate to the interface variable, you need not care about memory. But you have to be disciplined and never use a class, but use the interface and / or use as/is. This is not rocket science, but discipline. Actually you described the core difference between CORBA and COM and basically why CORBA is not a good idea for memory management: there is none in CORBA .... ---------------------------------------------------------------------- ArminLinder · 2023-09-07 12:00 Thinking about it a bit longer  ... Maybe I fell into my own trap :-) If I insist to see an interface as a means of defining objects all needing to support a defined set of properties and methods, creating an interface and storing that thing into a list (aNoiseSourceList) does not make much sense. Nevertheless this seemed a natural thing to me to do, to ensure type safety: the compiler won't let me add anything to the list if it does not support the interface. Good. The system seems to create the underlying objects, which is nice, but maybe not a good idea. Anyway, if the language lets me do it that way, it should give me a way to destroy those objects through the interface as well. @Thaddy: thanks for your efforts, but I have an idea what I want to achieve, and am not willing to jump on the COM interfaces yet Btw, browsing the Delphi docs, I found a better way to filter my objects. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   // a list of arbitrary objects and a filter  aDeviceList := [TCar.Create,TCat.Create,TFridge.Create];  for o in aDeviceList do    if o is IMovementInterface then TestMoveThingy(o as IMovementInterface); ---------------------------------------------------------------------- cdbc · 2023-09-07 12:43 Hi ONLY FOR CORBA interfaces! You could do, what you're not supposed to do e.g.:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   { INoiseInterface }   INoiseInterface = interface    function Obj: TObject; // surface the underlying class    procedure MakeNoise;  end; andCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   { TCar }   TCar = class(INoiseInterface, IMovementInterface)  private    function Obj: TObject;  public    procedure MakeNoise;    procedure Move;  end;   { TCat }   TCat = class(INoiseInterface, IMovementInterface)  private    function Obj: TObject;   public    procedure MakeNoise;    procedure Move;  end;   TElectricalThing = class    // anything you want to know about your electrical things, like wattage, weight, size, price, recyling, whatever  protected    function Obj: TObject;  end;   { TFridge }   TFridge = class(TElectricalThing, INoiseInterface)  public    procedure MakeNoise;  end; ex.:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   { TCat }  function TCat.Obj: TObject;  begin    Result:= Self;  end;   procedure TCat.MakeNoise;  begin    Writeln('Meow!');  end; ...and finally to use it:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   // using Intf.MakeNoise;  ...  Intf.Obj.Free;  Intf:= nil;  I guess this could solve your problem... Quote  for i in aNoiseSourceList do       testMakeNoise(i);   // cannot destroy, won't compile --> memory leak   for i in aNoiseSourceList do   //    i.Destroy;       i.Obj.Free; // <-- ONLY FOR CORBA INTERFACES!!! Btw. @PascalDragon is working on AS/IS for CORBA  Regards Benny ---------------------------------------------------------------------- ArminLinder · 2023-09-07 13:11 Quote from: cdbc on September 07, 2023, 02:43:43 pmBtw. @PascalDragon is working on AS/IS for CORBA  as/is: seems to be already implemented and released (3.2.2). See my edit to last post. Works like a charm, and relieved me from having to use Sysutils.Supports(). Thanks for your suggestion, I take it as a workaround for now, hoping someone knows a better way. If I go that route, I need to work over all interfaces and objects and add the "obj" method. Armin. ---------------------------------------------------------------------- valdir.marcos · 2023-09-07 15:31 Quote from: ArminLinder on September 07, 2023, 02:00:02 pmThinking about it a bit longer  ... Maybe I fell into my own trap :-)Be welcome! Interfaces in Pascal is a recurring subject of debate here: How to use interfaces https://forum.lazarus.freepascal.org/index.php/topic,56594.0.html How to use interfaces https://wiki.lazarus.freepascal.org/How_To_Use_Interfaces Understanding Interfaces https://wiki.lazarus.freepascal.org/Understanding_Interfaces Refactoring code to support some kind of multiple inheritance https://forum.lazarus.freepascal.org/index.php/topic,46181.msg328478.h tml#msg328478 Interface delegation https://forum.lazarus.freepascal.org/index.php/topic,54797.0.html (e-book in HTML and PDF) Modern Object Pascal Introduction for Programmers 10. Interfaces https://castle-engine.io/modern_pascal#_interfaces Edit: Quick Modern Object Pascal Introduction, for Programmers https://forum.lazarus.freepascal.org/index.php/topic,33095.0.html Updates to the "Modern Object Pascal Introduction for Programmers" https://forum.lazarus.freepascal.org/index.php/topic,37035.0.html Purpose of Classes https://forum.lazarus.freepascal.org/index.php/topic,47032.0.html Object Pascal Handbook as learning resource  https://forum.lazarus.freepascal.org/index.php/topic,51036.0.html Best Tutorial https://forum.lazarus.freepascal.org/index.php/topic,45078.0.html QuoteIf I insist to see an interface as a means of defining objects all needing to support a defined set of properties and methods, creating an interface and storing that thing into a list (aNoiseSourceList) does not make much sense. Nevertheless this seemed a natural thing to me to do, to ensure type safety: the compiler won't let me add anything to the list if it does not suppot the interface. Good. The system seems to create the underlying objects, which is nice, but maybe not a good idea. Anyway, if the language lets me do it that way, it should give me a way to destroy those objects through the interface as well. @Thaddy: thanks for your efforts, but I have an idea what I want to achieve, and am not willing to jump on the COM interfaces yet Btw, browsing the Delphi docs, I found a better way to filter my objects. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   // a list of arbitrary objects and a filter  aDeviceList := [TCar.Create,TCat.Create,TFridge.Create];  for o in aDeviceList do    if o is IMovementInterface then TestMoveThingy(o as IMovementInterface); ---------------------------------------------------------------------- nanobit · 2023-09-07 15:45 Quote from: ArminLinder on September 07, 2023, 01:45:35 pmThought, I had a good solution, but alas, my test program leaks memory. Well, I create objects for the list, so I need to destroy them as well. This is fairly easy for the list of objects (aDeviceList), but I failed to do it for the list of interfaces. How do I need to free the objects contained in aNoiseSourceList? It's very simple. You should not free the corba interface, but the object (owner). And all interfaces to this object are invalid after this. ---------------------------------------------------------------------- Remy Lebeau · 2023-09-07 16:11 Quote from: ArminLinder on September 07, 2023, 10:25:58 amIn my world (Java, c#) an interface is not an object. It does not take any memory, it is not created, not destroyed, and therefore there is no need for reference counting. That is because those environments use garbage-collection to manage object lifetimes.  Objects are kept alive as long as there are active references to them, whether that be object references or interface references. What you are looking for is more akin to how interfaces work in C/C++, which only contribute to object layout and not play into object lifetime management at all. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 16:19 Quote from: nanobit on September 07, 2023, 05:45:20 pmIt's very simple. You should not free the corba interface, but the object (owner). And all interfaces to this object are invalid after this. Sure. Please look at my sample. Test3 does exactly that, and works perfectly. The problem is Test2. Note that the array is declared of type INoiseInterface to utilize type safety. Unless I implement Bennys workaround, I found no way to get at the objects created to release them. Armin ---------------------------------------------------------------------- Remy Lebeau · 2023-09-07 16:23 Quote from: ArminLinder on September 07, 2023, 01:45:35 pmThought, I had a good solution, but alas, my test program leaks memory. Well, I create objects for the list, so I need to destroy them as well. This is fairly easy for the list of objects (aDeviceList), but I failed to do it for the list of interfaces. How do I need to free the objects contained in aNoiseSourceList? If you are using non-refcounted interfaces, then don't let the interface list hold the actual objects.  Instead, put the objects in a separate list that you can iterate when you are ready to free the objects.  Make the interface list just refer to the objects, not own them. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  aDeviceList: array of TObject;  aNoiseSourceList: array of INoiseInterface;begin  aDeviceList := [TCar.Create, TCat.Create, TFridge.Create];  SetLength(aNoiseSourceList, Length(aDeviceList));  for idx := 0 to Length(aDeviceList)-1 do    aNoiseSourceList[idx] := aDeviceList[idx] as INoiseInterface;  ...  for i in aNoiseSourceList do    testMakeNoise(i);  ...  for o in aDeviceList do     o.Destroy;end; ---------------------------------------------------------------------- ArminLinder · 2023-09-07 17:23 Remy, another fix witch creates another poblem :-) Syncing the list of object with the list of interfaces :-) Sure, I can now tuck a list of object and a list of interface together in a custom list ... If I compare the two workarounds, I consider Bennys to be the one I'd like more. It does fit my current mindset and my idea what I want to use interfaces for (in this special case) better. Not needing any workaround would however be preferred :-) Armin. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 17:40 Quote from: valdir.marcos on September 07, 2023, 05:31:02 pm Interfaces in Pascal is a recurring subject of debate here: That's exactly where I got stuck when I first tried to resolve the issue myself, by consulting the doc/wiki, and found them not being helpful. I feel fit I could add a paragraph about the CORBA style interface, probably including Bennys workaround, and I think it would help a lot. On the other side, if some Pascal heavyweight like Thaddy advises me to forget the CORBA interface style but look into the COM interfaces, who am I to disregard that. To make up my own mind, I would have to try to achieve my goals (see original post) using the COM style interfaces. If I find a better approach there, I would reason that CORBA interfaces are not to be used [any longer], and thus they should not be documented at all. Seems I traded inheritance hell for interface hell :-) Armin. ---------------------------------------------------------------------- alpine · 2023-09-07 18:02 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$interfaces corba} type  IDisposable = interface    procedure Dispose;  end;   { TDisposable }   TDisposable = class    procedure Dispose;  end;   { INoiseInterface }   INoiseInterface = interface(IDisposable)    procedure MakeNoise;  end;   { IMovementInterface }   IMovementInterface = interface(IDisposable)    procedure Move;  end;   { TDisposableCat }   TDisposableCat = class(TDisposable, INoiseInterface, IMovementInterface)  public    procedure MakeNoise;    procedure Move;  end; { TDisposable } procedure TDisposable.Dispose;begin  Self.Free;end;{ TDisposableCat } procedure TDisposableCat.MakeNoise;begin  Writeln('Meow!');end; procedure TDisposableCat.Move;begin  Writeln('Moved!');end; procedure Test;var  C: TDisposableCat;  NI: INoiseInterface;  MI: IMovementInterface;begin  C := TDisposableCat.Create;  NI := C;  MI := C;  NI.MakeNoise;  MI.Move;  NI.Dispose; // or MI.Dispose;end;               I don't think it's a hell at all. ---------------------------------------------------------------------- nanobit · 2023-09-07 18:25 Quote from: ArminLinder on September 07, 2023, 07:23:46 pmNot needing any workaround would however be preferred :-) Corba interfaces are very simple, but I use only Delphi compatible language, to support more compilers (who knows the future of FPC?). As shown by other forum members, you can directly call object.free or you need an additional interface-method to finally call object.free. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 18:32 Quote from: alpine on September 07, 2023, 08:02:38 pm I don't think it's a hell at all. I do :-) You turn the reason why I am so eager to use interfaces upside down. If you still want to use inheritance, which can indeed be very useful, you have just spent your single possible parent object reference on TDisposable. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   TDisposableCat = class(TDisposable, INoiseInterface, IMovementInterface)  public    procedure MakeNoise;    procedure Move;  end;  If you *still* want to use inheritance, you end up in "god object hell" with TDisposable, albeit to a far lesser extent. Armin. ---------------------------------------------------------------------- alpine · 2023-09-07 19:00 Quote from: ArminLinder on September 07, 2023, 08:32:32 pmYou turn the reason why I am so eager to use interfaces upside down. If you still want to use inheritance, which can indeed be very useful, you have just spent your single possible parent object reference on TDisposable. Actually, what exactly do you want to achieve? Quote from: ArminLinder on September 07, 2023, 08:32:32 pmIf you *still* want to use inheritance, you end up in "god object hell" with TDisposable, albeit to a far lesser extent. Don't inherit from it! Write Dispose for each class if you wish. It is your call. As a matter of fact, the COM interfaces can take care of your instances, see Thaddy's post. ---------------------------------------------------------------------- ArminLinder · 2023-09-07 19:35 Guys, really, thank you for your patience. I had this idea in mind how I wanted to write my code, and was not easily willing to give that up. For my curent purpose, though it is a bit of work, Bennys approach looks cleanest to me. I am however seriously considereing to give up on CORBA interfaces entirely. I ran into the next unexpected behaviour. Remember: I got everything I wanted, except Test2. I thought, I get type safety, since this is correctly rejected by the compiler: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   [...]  writeln(' ------- Test 2 ------- ');  // a list of noise-making objects  aNoiseSourceList := [TCar.Create,TCat.Create,TFridge.Create,TTestObject.Create];  for i in aNoiseSourceList do      TestMakeNoise(i);  // for i in aNoiseSourceList do  //    i.Destroy;[,,,]  with TTestObject being an arbitrary object not implementing INoiseInterface. Trying to add it, gives a compiler error: project2.lpr(124,74) Error: Incompatible types: got "TTestObject" expected "INoiseInterface" Great. Unfortunately type safety is not always enforded: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   aNoiseSourceList := aNoiseSourceList + [TTestObject.create]; is accepted (need {$modeswitch arrayoperators+} for this to work at all). To stay type-safe I could use the 2 step approach to append to the array: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   SetLength(aNoiseSourceList,length(aNoiseSourceList)+1);  aNoiseSourceList[length(aNoiseSourceList)-1] := TTestObject.create; // rejected by the compiler as expcted  But that has always looked quite clumsy to me. Maybe tehre were otehr array types giving besser results, but seriously, IMHO I am just trading problems, not resolving them. Armin. P.S. I really don't want to waste your precious time. I did, I admit, stubbornly cling to an approach I had in mind (think I saw it in C#), because it looked so logical to me. Pascal obviously cannot do things that way, maybe I switch to COM interfaces tos ee wether that fits my coding style better, and if not, I have more than one workaround, so those who don't want to carry on: thanks for your contribution. Those who still stay: thanks for your patience.