New MemoryBlock.Clone does not work if created from a Ptr

Let’s say you have this code:

dim mb1 as new Xojo.Core.MemoryBlock( somePtr, theSize )
dim mb2 as Xojo.Core.MemoryBlock = mb1.Clone

You’d expect mb2 to be a copy of the data in mb1, right? Well, it’s not. mb2 ends up pointing to mb1. If mb1 has been created “normally”, it works as expected.

See here for the report and a demo project:


Might be a really dumb question, but what if you use new on the second memory block?

Same result.

The docs say:

[quote]Clone As MemoryBlock
Makes a copy of the MemoryBlock. If its size is unknown, it copies the content.[/quote]
Does that mean if the size is known it does not copy the content?

Hm… is it really a bug?

IIRC the Xojo.Core.MemoryBlock is not mutable. So if I need another one with the same content: what’s wrong when the same address ist used? It just saves memory.

@Paul Lefebvre is fixing that typo now.

@Thomas Eckert, yes, this has to be a bug. If you want another MemoryBlock that just points to the original, or part of the original, there are other ways to do that. More, if the original MemoryBlock was created in the “standard” way, this works as expected.

For example, mb2 = mb1.Left( partial ) does not clone and saves memory exactly as you’d hope. But in my case, I had to make a copy before modifying the original data. Imagine my surprise when my copy kept changing too. I finally had to do it this way:

dim originalData as new Xojo.Core.MutableMemoryBlock( data.Size )
originalData.Left( data.Size ) = data

But in the initial post you use a Xojo.Core.MemoryBlock and no Xojo.Core.MutableMemoryBlock.
For the latter I see the need to make a copy because it is changed.
I really don’t see the need for a “real copy” in case a non mutable MemoryBlock is used.

Well, I think a non mutable MemoryBlock is just “read only” memory and so it is fine that another MemoryBlock with the same content does use the same memory address.

I am really wrong here with my thoughts?

I see your reasoning, but in my project, it’s actually the opposite. The original is a MutableMemoryBlock and I’m trying to copy it into a MemoryBlock. I used MemoryBlock in my examples for simplification, but still, Clone should do what it says and make a copy regardless.

This works too, btw:

dim originalData as new Xojo.Core.MemoryBlock( data.Left( data.Size ) )

Again, data is a MutableMemoryBlock.

A little background: This came about as I am transitioning a project from the old MemoryBlock to the new. As I am doing it in parts, I used code like this:

MethodThatWantsAMemoryBlock( oldMb )

// became

dim newMb as new Xojo.Core.MutableMemoryBlock( oldMb, oldMb.Size )
MethodThatWantsAMemoryBlock( newMb )

This works because newMb is not a clone so changes to it are automatically reflected in oldMb, but within that now-updated function, I have to clone its data, and that’s where it failed.

I see. Thanks.