Thinking about memory blocks

I have been wondering if a MemoryBlock can nest other memory blocks.

Var ParentMB As New MemoryBlock(100)

Var LeftPtr  As Ptr = ParentMB
Var RightPtr As Ptr = ParentMB + 50

Var LeftMB  As MemoryBlock = LeftPtr.MemoryBlock(50)
Var RightMB As MemoryBlock = RightPtr.MemoryBlock(50)

Does this seem correct to you?
Like lets just say that the first 50 bytes are big endian and the last 50 are little endian.

Well, sort of. You can certainly create a Ptr that points to an arbitrary starting point within a MemoryBlock, and you can create a MemoryBlock out of a Ptr, albeit with an unknown size, then set each MemoryBlock.LittleEndian independently.

Here is code that works:

var parentMb as new MemoryBlock( 16 )

var leftPtr as ptr = parentMb
var rightPtr as ptr = ptr( integer( leftPtr ) + 8 )

var leftMb as MemoryBlock = leftPtr
var rightMb as MemoryBlock = rightPtr

leftMb.LittleEndian = true
rightMb.LittleEndian = false

leftMb.UInt64Value( 0 ) = 1
rightMb.UInt64Value( 0 ) = 1

// Result is
//  01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01

Once you do this, you must use the MemoryBlock functions instead of the Ptr calls since the latter will always use the system’s LittleEndian property.

Edit: What is your use case for this though? I would think using two MemoryBlocks and combining them later using CopyBytes would be just as fast, and safer.

Just get ptr to both areas and pass on ptr and size.

But of course why not just use two memory blocks?

This particular file format switched endianness in several places and is composed of recursively nested structures.. it’s fun. I just had the suspicion that some additional memcpy’s might be happening that i wish to avoid.

I see.

You might be better off forgoing Ptr entirely and just switching LittleEndian as you go.

Example:

var mb as MemoryBlock = ReadData()

mb.LittleEndian = false
var firstValue as integer = mb.Int64Value( 0 )

mb.LittleEndian = true
var secondValue as integer = mb.Int64Value( 8 )

Exactly.. but I wanted two (actually likely hundreds) of sections within the memory block.

So when you ‘create’ a memory block from a pointer you specify how many bytes that pointer points to?

Why do you need so many sections? What is the structure of the data?

No, you create a pointer that points to an existing memory block.

I’d go with Kem’s suggestion. (If I had a nickel for every time I said that.)

1 Like

It’s more like, you create a MemoryBlock around a Ptr. Such a MemoryBlock will start at the Ptr address and allow you to use its functions, but doesn’t know its dimensions.

Consider this code:

var parentMb as new MemoryBlock( 1 )
var p as ptr = parentMb

var otherMb as MemoryBlock = p

otherMb.UInt64Value( 0 ) = 1

This will work because otherMb doesn’t know its bounds, but you will end up overwriting memory locations that are outside of the reserved space, and your app will eventually crash. Hard.