Hello,
what is the most idiomatic way to modify memory directly ???
I need this to write to memory (memory mapped IO of a MCU) or read from . I found the ptr type. But the documentation only show to use it in combination with addr.
Is there a pragma or should I use a cast ?
best regards
Andreas
Well, this largely depends on how you want to read or write to the piece of memory. You can cast a pointer to the raw memory to a data type, such as an unchecked byte array (I do something like this when parsing data placed in a buffer I've given to the OS), and you can also use the procedures for copying and moving memory. Here's an example:
type byteBuffer {.unchecked.} = array[1, byte]
when isMainModule:
let rawPtr: Pointer = getMemoryPtr()
let buffer = cast[ByteBuffer](rawPtr)
(I can't remember at the moment whether that cast type should be ptr ByteBuffer or just ByteBuffer)
template `+!`(p, i): expr = cast[type(p)](cast[int](p) +% i)
How map C structures
#pragma pack(push) #pragma pack(1)
struct MyStruct { int32_t bufLen; int32_t used; char buf[1]; };
#pragma pack(pop)?
to nimrod type and cast memory pointer to it|
type
MyStruct {.packed.} = object
bufLen, used: int32
buf: array [1, char]
var p: pointer = ...
cast[ptr MyStruct](p).bufLen = 12