Just use a dummy procedure following the code and substract the two, eg:
procedure Code
asm
call ebx;
end;
procedure CodeEnd;
asm end;
CodeSize := DWORD_PTR(@CodeEnd) - DWORD_PTR(@Code);
CopyMemory(@MyByteArray[0], @Code, CodeSize);
Note that in code you use also use Delphi code instead of asm as long as you don't call into other code (functions/procedures/rtl)
EDIT: as an answer to the comments from Serg and David Heffernan I verified the results with Delphi 2010 in release mode.
I used the following code:
procedure Code;
asm
mov eax, 0;
end;
procedure CodeEnd;
asm end;
procedure TForm4.Button1Click(Sender: TObject);
begin
ShowMessageFmt('CodeSize=%d', [DWORD_PTR(@CodeEnd) - DWORD_PTR(@Code)]);
end;
The reported CodeSize is 8 Bytes, I then verified using Ida Pro (disassembler on the executable):
.text:004B3344 Code proc near
.text:004B3344
.text:004B3344 B8 00 00 00 00 mov eax, 0
.text:004B3349 C3 retn
.text:004B3349 Code endp
.text:004B3349
.text:004B3349 ; -----------------------------
.text:004B334A 8B C0 align 4
So in this example mov eax, 0 is 5 bytes (B8 00 00 00 00), retn (added by compiler) is 1 byte (C3), align 4 is 2 bytes (8B C0) which is 8 in total.