How can I point an array to existing data in memory while using Better C?

sarn sarn at theartofmachinery.com
Sun Jul 8 22:33:14 UTC 2018


On Sunday, 8 July 2018 at 21:11:53 UTC, Stijn Herreman wrote:
> On Sunday, 8 July 2018 at 20:27:34 UTC, Stijn Herreman wrote:
>> I should point out that I only have a vague idea of what I'm 
>> doing, I tried things until it compiled and worked (at first 
>> glance). If there are any docs that properly explain the 
>> casting of pointers, I'd appreciate the links.
>
> I found the following works as desired:
>
> environment.d
>
>     public __gshared header* GPT_header;
>     public __gshared partition_entry* GPT_entries;
>
> main.d
>
>     GPT_header = cast(header*)0x00007e00;
>     GPT_entries = cast(partition_entry*)0x00008000;
>
> That still lets me access GPT_entries with an index, e.g. 
> GPT_entries[0]. Is this how it's supposed to be done, or is 
> there a better way still?

You can also easily make slices out of pointers.  E.g.:

// Some backing memory
int[10] x;
// Take a pointer
int *xp = x.ptr;
// Convert pointer to D slice
int[] x2 = xp[0..10];
assert (x2.length == 10);

(Of course, you don't need to break it into steps in real code, 
and it works fine in betterC.)

There's still not a lot of info out there about doing betterC, 
but maybe you can find some examples in the following code.  It 
works without any druntime at all, including TypeInfo.  This is 
the entry point after a bootloader loads the D code and enters 
32b protected mode:
https://gitlab.com/sarneaud/xanthe/blob/master/src/os/drivers-bios.d#L198


More information about the Digitalmars-d-learn mailing list