How can I get direct access to memory? I have table:
And I want to get access to it (each byte, one by one) via memory address (read it, and change).Code:Dim bytTable(500) As Byte
Printable View
How can I get direct access to memory? I have table:
And I want to get access to it (each byte, one by one) via memory address (read it, and change).Code:Dim bytTable(500) As Byte
Since VB.NET doesnt support pointers you'd have to use the members of the Marshal class.
First you need to get the base address of the array:
Then you could create a new IntPtr pointing to a specific element by doing:VB.NET Code:
Dim baseAddress As IntPtr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(table, 0)
Then write whatever you want on that address:VB.NET Code:
Dim newAddress As New IntPtr(baseAddress.ToInt32() + 5) 'Will point at the 4th element.
VB.NET Code:
System.Runtime.InteropServices.Marshal.WriteByte(newAddress, 0, 200)
Though creating a new IntPtr isnt really necessary since the WriteByte method allows you to specify the offset. So this has the same effect as above:
VB.NET Code:
System.Runtime.InteropServices.Marshal.WriteByte(baseAddress, 5, 200)
Another way to go about all this is to specify what element you want to retrieve the address to in the call to UnsafeAddrOfPinnedArrayElement.
Thanks, great code ;)
It looks to be extremely slow... It works, but much slower than the same action on table. There isn't any faster way to change bytes than via table?
It would be slower, because when you access an arrays element "normally" (ie by specifying index like so: bytTable(index)) what happens under the hood is simple arithmetics.
With these methods we get an extra layer of complexity versus the normal way.
I dont know of any faster way to access an arrays elements unfortunately, but I'll keep looking for a while.
Thanks. I created new thread about it, so there (I hope) discussion will be continued.