Delphi: how to set the length of a RTTI-accessed dynamic array using DynArraySetLength?

后端 未结 2 778
你的背包
你的背包 2021-01-21 00:41

I\'d like to set the length of a dynamic array, as suggested in this post. I have two classes TMyClass and the related TChildClass defined as

TChildClass = class         


        
2条回答
  •  悲哀的现实
    2021-01-21 01:19

    Dynamic arrays are kind of tricky to work with. They're reference counted, and the following comment inside DynArraySetLength should shed some light on the problem:

    // If the heap object isn't shared (ref count = 1), just resize it. Otherwise, we make a copy

    Your object is holding one reference to it, and so is the TValue. Also, GetReferenceToRawData gives you a pointer to the array. You need to say PPointer(GetReferenceToRawData)^ to get the actual array to pass to DynArraySetLength.

    Once you've got that, you can resize it, but you're left with a copy. Then you have to set it back onto the original array.

    TValue.Make(@ArrPointer, dynArr.Handle, ArrValue);
    RField.SetValue(val.AsObject, arrValue);
    

    All in all, it's probably a lot simpler to just use a list instead of an array. With D2010 you've got Generics.Collections available, which means you can make a TList or TObjectList and have all the benefits of a list class without losing type safety.

提交回复
热议问题