Invalid Pointer operation in TEntityMap.FinalizeItem

Issue #312 resolved
Inkvizi created an issue

When an entity is cloning to put into TEntityMap and the entity contains a field with object which contains the field of pointer type we finally have two objects with two fields referensing the same pointer in memory. So when one of them will be destroyed - he will clean the pointer and free memory. Another one will cause Invalid Pointer operation exception when it is going to be destroyed.

  procedure CopyFieldValues(const source, target: TObject);
  var
    field: TRttiField;
    value: TValue;
    sourceObject, targetObject: TObject;
  begin
    Assert(Assigned(source) and Assigned(target));
    Assert(source.ClassType = target.ClassType);

    for field in TType.GetType(source.ClassInfo).GetFields do
    begin
      if field.FieldType.IsInstance then
      begin
        sourceObject := field.GetValue(source).AsObject;
        if not Assigned(sourceObject) then
          Continue;
        targetObject := field.GetValue(target).AsObject;
        if not Assigned(targetObject) then
          targetObject := TActivator.CreateInstance(sourceObject.ClassType);
        if targetObject is TPersistent then
          TPersistent(targetObject).Assign(sourceObject as TPersistent)
        else
          CopyFieldValues(sourceObject, targetObject);
        value := targetObject;
      end
      else
        value := field.GetValue(source); //<== Get a pointer of TMemoryStream.FMemory for example

      field.SetValue(target, value);  // <== Set a same pointer of TMemoryStream.FMemory
    end;
  end;

Comments (3)

  1. Log in to comment