Internal work "fixed": work on a location or memory object?

In managed / unmanaged compatibility of arrays, I have a case of the absence of the usual

fixed (byte* data = new byte[length]) { // work with the array } 

but I want to bind an array where I get the link, for example:

 IntPtr dataPtr = camera.Image2d.GetDataBuffer(); fixed (byte* data = (byte *)dataPtr) { // work with the array } 

1) In my opinion, the lower code should also work, since "fixed" will set the memory level in the memory manager low and does not care about any objects pointing to it? (Meaning, I don't have a "root" / direct pointer - although there probably is no such thing.)

One more question:

2) The requirement to use "fixed" comes from the CLR memory manager, working simultaneously with any executed code, so it can move arrays at any time?

+4
source share
1 answer

1) the second does not seem to be correct, since the fixed keyword is used, which you are trying to attach a pointer, not the actual object. And IntPtr not (afaik) a managed pointer, not an unmanaged one.

2) fixed creates a pointer to the specified managed variable; and without fixing, GC can move the variable to another memory location, so the pointer will become useless.

from msdn :

A fixed statement sets a pointer to a managed variable and "contacts" this variable during the execution of an instruction. Without a fixed, pointers to movable managed variables will be of little use, since garbage collection can move variables unpredictably. The C # compiler allows you to assign a pointer to a managed variable in a fixed statement.

+3
source

All Articles