In a C# to native lib CLI/C++ wrapper, I have a choice:
- Store native pointer in a managed class (native object is created using native "new")
or
- Store native object as a data blob in a managed class' field, and use
pin_ptrto pin it before each native use.
Has anyone done any comparative analysis on the relative performance costs of the two paths?
Thanks!
pin_ptr is to prevent objects on the managed heap from being moved by the GC when its address is being passed to native function functions who aren't aware the chair could be pulled by the GC. It does not affect memory allocated on the native heap or on the stack.
Storing native object as blob in a managed class is what managed C++ did for mixed types. It was too easy to returns a pointer to memory on the garbage collected heap that is not pinned and could crash the app later on, and this problem is too hard to debug. This problem is so common (people do not expect the chair can be pulled by GC) that Microsoft decided to disable mixed type altogether so people have to explicitly specify where the object's memory is.