我在Delphi中有这样一个基本问题,我无法解决它.
我的代码:
注意:DataR在下面的方法中是本地的,但通常它是一个类var.Just为它的本地概念.
class procedure TCelebrity.BeginRead(var input:Array of byte);
var DataR:Array of byte;
begin
VirtualFree(@DataRead,High(DataRead),MEM_RELEASE);
SetLength(DataR,Length(input));
Move(input,DataR,Length(input));
end;
Run Code Online (Sandbox Code Playgroud)
这个编译,但执行Move()后DataR = nil.
第二次尝试:
class procedure TCelebrity.BeginRead(var input:Array of byte);
var DataR:Array of byte;
begin
VirtualFree(@DataRead,High(DataRead),MEM_RELEASE);
SetLength(DataR,Length(input));
DataR := Copy(input,0,Length(input));
end;
Run Code Online (Sandbox Code Playgroud)
这不会编译在所有.第三行的错误(DataR:=复制(输入....)说"不兼容的类型".
哪里出了问题?它们都是字节数组!
小智 8
试试这个
type
TByteDynArray = array of Byte;
function CopyData(const Input:array of Byte):TByteDynArray;
begin
SetLength(Result, Length(Input));
Move(input[0], Result[0], Length(Input));
end;
Run Code Online (Sandbox Code Playgroud)
为什么不使用FOR?
SetLength(DataR,Length(input));
for i:=Low(input) to High(input) do
DataR[i]:=input[i];
Run Code Online (Sandbox Code Playgroud)
顺便说一句:如果你想让数组作为参数传递,你应该将它们声明为一个类型,例如:
type
TMyArray = array of byte;
Run Code Online (Sandbox Code Playgroud)
并使用TMyArray作为参数类型.
编辑:我收到了关于价值较低的通知.在我原来的帖子中,它是i:= 0,但我:=低(输入)更安全,更纯净.
| 归档时间: |
|
| 查看次数: |
19841 次 |
| 最近记录: |