   [.net] Can I make some objects not garbage collected?
  I'm trying to mix some unmanaged code with managed code, and I need a way to prevent my managed wrapper class from being garbage collected, since I keep getting memory access violations.  My wrapper class is wrapping up my native game engine stuff from the .NET winform gui that I'm making.  One method I tried was to use pin_ptr on the wrapper class' internal data but that doesn't work, since the pinning stops working when it goes out of scope, and there doesn't seem to be a way to make a pinned member function.Is there some way that I can just keep either my wrapper class or all of it's contents off the GC heap?Thanks.   
  For this problem I made a class to work as a interface for the unmanaged library that's object would stay in use as long as the library was in use that has a List<Object> to store all the objects used by unmanaged code.EDIT:If you really wanted you could just put the List<Object> in a static class but its better oop to just have a class that represents the unmanaged library.   ;  pin_ptr is basically a wrapper around GCHandle. If you allocate a GCHandle like this:GCHandle handle = GCHandle::Alloc(myObject, GCHandleType::Pinned);The object won't get moved around by the garbage collector. Note that this is probably bad for garbage collector performance and memory fragmentation, so only keep the handle around as long as you need it. Once you're done with it, use the Free() method of the handle to make sure you give control back to the garbage collector.   ;  It gives me an exception:Object contains non-primitive or non-blittable data.I'm using it on my managed wrapper class that contains my unmanged engine stuff.  That exception doesn't happen if I use a Normal GCHandle, but then it doesn't do what I originally intended.  Is there another way to make my unmanaged engine sit in the corner separately from my managed stuff?   ;  Ok, forget the wrapper class idea; is there a way to keep my unmanaged stuff that is in it from being touched by the GC?  Whenever I try to deference any pointers to unmanaged data, my program explodes.   ;  You can only pin objects that make sense to pin, which means simple types, usually ones intended to replicate native structures.It sounds like you screwed up. A managed wrapper will typically have a pointer to the unmanaged instance, and the functions of the managed wrapper will forward to the unmanaged internal pointer, marshaling args and the return values as necessary. You shouldn't need to pin anything most of the time. In particular, note that your unmanaged instance lives on the native heap and is not subject to GC in the first place. Only your pointer is being moved around, which obviously doesn't matter.   