www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Pointers and offsets

reply "Bauss" <jj_1337 live.dk> writes:
Is it possible to access a pointer by its offsets.
Ex. write a 32bit integer to a byte pointer at ex. offset 4.


fixed (byte* Packet = Buffer) // Buffer would be a byte array

And then to set the value of a specific offset
*((TYPE*)(Packet + OFFSET))

Where TYPE could be replaced by ex. uint and OFFSET by 4

I tried to look here:
http://dlang.org/arrays.html

But couldn't seem to find anything like it.
Jan 13 2015
next sibling parent reply "Bauss" <jj_1337 live.dk> writes:
On Wednesday, 14 January 2015 at 01:16:54 UTC, Bauss wrote:
 Is it possible to access a pointer by its offsets.
 Ex. write a 32bit integer to a byte pointer at ex. offset 4.


 fixed (byte* Packet = Buffer) // Buffer would be a byte array

 And then to set the value of a specific offset
 *((TYPE*)(Packet + OFFSET))

 Where TYPE could be replaced by ex. uint and OFFSET by 4

 I tried to look here:
 http://dlang.org/arrays.html

 But couldn't seem to find anything like it.
Can't seem to edit OP so at: *((TYPE*)(Packet + OFFSET)) It should be: *((TYPE*)(Packet + OFFSET)) = VALUE; VALUE has to be of the same type as TYPE of course.
Jan 13 2015
parent Mike Parker <aldacron gmail.com> writes:
On 1/14/2015 10:17 AM, Bauss wrote:
 On Wednesday, 14 January 2015 at 01:16:54 UTC, Bauss wrote:
 Is it possible to access a pointer by its offsets.
 Ex. write a 32bit integer to a byte pointer at ex. offset 4.


 fixed (byte* Packet = Buffer) // Buffer would be a byte array

 And then to set the value of a specific offset
 *((TYPE*)(Packet + OFFSET))

 Where TYPE could be replaced by ex. uint and OFFSET by 4

 I tried to look here:
 http://dlang.org/arrays.html

 But couldn't seem to find anything like it.
Can't seem to edit OP so at:
The forum is a web interface to a newsgroup, which also has a mailing list interface. So no, no editing.
 *((TYPE*)(Packet + OFFSET))

 It should be:
 *((TYPE*)(Packet + OFFSET)) = VALUE;

 VALUE has to be of the same type as TYPE of course.
void main() { ubyte[16] bytes; for( int i=0; i<4; ++i ) { *(cast( int* )( bytes.ptr + (i*4))) = i; } import std.stdio : writeln; writeln( cast( int[] )bytes ); }
Jan 13 2015
prev sibling parent ketmar via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> writes:
On Wed, 14 Jan 2015 01:16:52 +0000
Bauss via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> wrote:

 Is it possible to access a pointer by its offsets.
 Ex. write a 32bit integer to a byte pointer at ex. offset 4.
yes, it is. it's same as in c/c++, except that you have to add one magic word: `cast`. D specs has it all.
Jan 14 2015