开发者

Delphi: problem setting length of a TByteDynArray

开发者 https://www.devze.com 2023-01-05 03:36 出处:网络
Question closed (answer accepted) replaced by Delphi 7: Access violation - TByteDynArray problem) I have the following delcartion given to me

Question closed (answer accepted) replaced by Delphi 7: Access violation - TByteDynArray problem)


I have the following delcartion given to me

MyPhoto = class(TRemotable)
private
  FhasPhoto: Boolean;
  FphotoData: TByteDynArray;
published
  property hasPhoto: Boolean read FhasPhoto write FhasPhoto;
  property photoData: TByteDynArray read FphotoData write FphotoData;
end;

and I want to

var photo : MyPhoto;
photo := MyPhoto.Create();
SetLength(photo.photoData, 4);

but I get

[Error] mainForm.pas(340): Constant object cannot be passed as var开发者_如何学C parameter

1) How do I code it correctly, given that I can't change the definition of the class Photo?

2) can I effectively 'cast' any structure to a TByteDynArray just by assigning it?

(as you might have guessed, I'm a BCB guy trying to get into Ddlphi :-)


p.s I will settle for being able to assign each byte of the photo data individually...


This is a flaw in Delphi's implementation of properties. Even if the property can be read and written to, even if both the read and the write point to the same field in the underlying object, you can't pass a property to a var parameter, such as to SetLength. There's no good reason for this, but that's the way it works, for the time being at least.

There's a fairly simple workaround for this issue, though. You need a method on the object that takes an integer and will set the length of FPhotoData internally.


Here is a way :

MyPhoto = class(TRemotable)
  ...
public
  procedure SetSize( aSize : Integer );
end;

procedure MyPhoto.SetSize( aSize : Integer );
begin
  SetLength( FphotoData, aSize );
end; 


var photo : MyPhoto;
photo := MyPhoto.Create();
MyPhoto.SetSize(4);
0

精彩评论

暂无评论...
验证码 换一张
取 消