在Delphi中使用偏移量复制内存

6
我想要复制一个有偏移量的内存块,这个能实现吗?
以下是目前我拥有的代码:
const
  SOURCE: array [0..5] of Byte = ($47, $49, $46, $38, $39, $61);
var
  Destination: Pointer;
begin
  // This is a full copy
  Move(SOURCE, Destination^, SizeOf(SOURCE));

  // If i want to copy from the third byte, is it possible?
  // I imagine the code should be, but it cannot be compiled.
  Move(Slice(SOURCE^, {Offset=}2)^, Destination^, SizeOf(SOURCE) - 2);
end;

在做类似这样的事情时,请注意使用 SizeOf(Source)通常是创建缓冲区溢出的好方法-您应始终确保移动的数据量适合目标缓冲区。 - Mad Hatter
2个回答

9
“不完全清楚你想要达到什么目的,但看起来…”
MoveMemory(pointer(NativeUInt(Destination) + 2), @SOURCE[0], SizeOf(SOURCE) - 2)

尽管我觉得你实际上想要的是什么。
MoveMemory(pointer(NativeUInt(Destination) + 2), @SOURCE[2], SizeOf(SOURCE) - 2)

请注意,Move 接受参数 Source, Dest, Count,而 MoveMemory 接受 Dest, Source, Count。此外,前者需要标识符,而后者需要指针。 - Andreas Rejbrand
是的。@SOURCE[2] 恰好是我想要的。谢谢。 - stanleyxu2005
安德烈斯,你为什么要将目标偏移2个单位?我理解这个问题是从源地址复制并偏移2个单位到目标地址。可以使用MoveMemory( pt, @SOURCE[2],SizeOf(SOURCE)-2);或者Move( SOURCE[2],pt^, SizeOf(SOURCE)-2);来实现。 - LU RD
@LU RD:仅仅因为我没有完全理解OP的意思。 - Andreas Rejbrand
好的,我能接受这个 :) 只是想评论一下,以防有人认为需要使用一些指针技巧,但实际上并不需要。 - LU RD

2

要使用 Move() 来复制数组的一部分,请按照以下方式进行:

Move(SOURCE[Offset], Destination^, SizeOf(SOURCE)-Offset); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接