A bit of history - there is some_lib.dll library (implemented in visual studio), using regasm I register and create a type library, which I later import into the delphi project with the creation of wrappers. In Delphi, the following code:

procedure DoSomething(); var _id: Integer; _class: TClass; // TClass - класс из файла-обертки библиотеки типов _obj: OleVariant; // ссылка на объект, созданный после вызова одной из функций dll begin try _id := 123; _class := TClass.Create(nil); _obj := _class.GetObject(123); // создаем объект, возвращаем ссылку _class.TreatObject(_obj); // передаем ссылку в другой метод, обрабатываем объект _class.TreatObjectAgain(_obj); // передаем ссылку в третий метод, опять что-то с ним делаем finnaly _class.Free; // _obj ??? end; end; 

The question is - how to properly free the memory occupied by the _obj? As far as I understand, the object will remain in memory after the function completes.

  • one
    Will not stay. Too lazy to write an answer, maybe someone will reach their hands - then I will delete the comment. If the resulting object is a COM interface, and indeed any interface (most likely it is), then its links ( AddRef / Release ) automatically go and when the normal implementation of the original dll comes out of DoSomething it will be destroyed, because . the reference count to it will reach 0. In general, FastMM and analogs are in your hands :) - kami

1 answer 1

OleVariant refers to autorun types (as well as Variant, String, AnsiString, WideString, UnicodeString, dynamic arrays, interfaces). This means that (roughly speaking) the compiler will automatically clear the variable when it leaves the zone of visibility. Manually freeing such variables should not be, it is strictly necessary only in the following cases:

  1. Unloading the DLL in which the variable was allocated, up to the point where the automatic cleaning takes place ( for example , see "Pitfall: mixing manual and automatic lifetime control")
  2. Freeing the dynamic memory in which the variable itself is located (for example, an auto-controlled variable as a record field with a dynamic allocation through a pointer)
  3. Premature cleaning to reduce memory consumption
  4. Manual lifetime control

If your code has problems when working with OleVariant (as well as with other autonomous types), this means that you made a mistake during manual control. For example . Or such (see. "Error: returning complex types through Result"). But this does not mean that you forgot to free up memory, as it could be for unmanaged classes / objects.

In any case, any variables of autorun types can always be manually cleared at any time by calling Finalize for them.