#1 2025-01-23 15:41:40

youssef
Member
Registered: 2024-08-05
Posts: 9

Issue with RTTI for Records

Hello everyone,

I am encountering an issue when attempting to use RTTI (Run-Time Type Information) in Delphi to convert a record into a dynamic TDocVariantData. My goal is to loop through all fields or properties of a record and dynamically build a variant structure.

function RecordToDocVariant<T>(const ARecord: T): Variant;
var
  Ctx: TRttiContext;
  Typ: TRttiType;
  Prop: TRttiProperty;
begin
  Result := TDocVariantData.New;
  Ctx := TRttiContext.Create;
  try
    Typ := Ctx.GetType(TypeInfo(T)); // Retrieve RTTI for type T
    if Typ = nil then
      raise Exception.Create('RTTI not available for the type');

    for Prop in Typ.GetProperties do
    begin
      Result.AddValue(Prop.Name, Prop.GetValue(@ARecord).AsVariant);
    end;
  finally
    Ctx.Free;
  end;
end;

Example Call
Here’s how I’m calling the function:

var
  MyRecord: TMyRecord;
  DocVariant: Variant;
begin
  MyRecord.ID := 123;
  MyRecord.Code := 'ABC123';

  DocVariant := RecordToDocVariant<TMyRecord>(MyRecord);
  WriteLn(DocVariant.ID);      
  WriteLn(DocVariant.Code); 
end;

Offline

#2 2025-01-23 18:01:43

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,839
Website

Re: Issue with RTTI for Records

Why are you using the Delphi RTTI?

What is your problem?

The easiest is to use pure mORMot and some in-between JSON.
And use TDocVariantData and not variant late binding.

Edit: Or try https://github.com/synopse/mORMot2/commit/c6cf2db04

Offline

#3 2025-01-25 10:12:43

youssef
Member
Registered: 2024-08-05
Posts: 9

Re: Issue with RTTI for Records

I am trying to find a way to get record values and store them in docVariantData without using serialization/deserialization  ?

Last edited by youssef (2025-01-25 10:20:10)

Offline

#4 2025-01-25 17:57:18

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,839
Website

Re: Issue with RTTI for Records

The new GetVariantFromRtti() function can do it.
Using JSON serialization internally by now, but it is not a slow operation.

Offline

Board footer

Powered by FluxBB