SImple C++ code to D
bearophile via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 13 13:03:39 PDT 2014
Alexandre:
> WORD e_res[4];
In D it's better to write:
WORD[4] e_res;
> char image[0x800];
Note this is a thread-local variable. If you need a module-local
variable you have to write:
__gshared char[0x800] image;
> void main(string[] args)
If you don't need the args, then write:
void main()
In D we usually indent using 4 spaces.
> auto dosh = cast(IMAGE_DOS_HEADER*)&image[0];
Perhaps better (untested):
auto dosh = cast(IMAGE_DOS_HEADER*)image.ptr;
> dosh.e_magic = cast(WORD*)("MZ");
Try (assuming word is 2 bytes long):
dosh.e_magic = cast(WORD*)"MZ".ptr;
> auto stub = [0xb8, 0x01, 0x4c, 0xcd, 0x21];
Try to use:
immutable ubyte[5] stub = [0xb8, 0x01, 0x4c, 0xcd, 0x21];
> dmemcpy(&image[0x40], stub, stub.sizeof);
> }
>
> void * dmemcpy ( void * destination, const void * source,
> size_t num ) pure nothrow
> {
> (cast(ubyte*)destination)[0 ..
> num][]=(cast(const(ubyte)*)source)[0 .. num];
> return destination;
> }
In D most cases you can avoid to use "void" as argument type.
Also try to minimize the use of casts.
And in D the "*" of pointers is written on the left, so you write
"int* p" and not "int *p".
Also in that function you don't mutate "num", so put a "in"
before "size_t".
> But I got errors in this:
> dmemcpy(&image[0x40], stub, stub.sizeof);
What errors?
Your code with some changes, but more improvements are possible
(untested):
import std.stdio;
import core.stdc.string;
import std.c.windows.windows;
struct IMAGE_DOS_HEADER {
WORD e_magic,
e_cblp,
e_cp,
e_crlc,
e_cparhdr,
e_minalloc,
e_maxalloc,
e_ss,
e_sp,
e_csum,
e_ip,
e_cs,
e_lfarlc,
e_ovno;
WORD[4] e_res;
WORD e_oemid;
WORD e_oeminfo;
WORD[10] e_res2;
LONG e_lfanew;
}
alias PIMAGE_DOS_HEADER = IMAGE_DOS_HEADER*;
__gshared char[0x800] image;
void main() {
auto dosh = cast(IMAGE_DOS_HEADER*)image.ptr;
dosh.e_magic = cast(WORD)*"MZ".ptr;
immutable stub = x"b8 01 4c cd 21";
memcpy(&image[IMAGE_DOS_HEADER.sizeof], stub.ptr,
stub.length);
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list