[Mono-dev] boehm and pin to sgen and moveable

Jonathan Mitchell jonathan at mugginsoft.com
Sat Oct 3 14:25:37 UTC 2015

In my ObjC->Mono bridge I have been using the Boehm collector and pinned memory (as an expedient).
I now want to move to SGEN and moveable memory.
As a first step I have switched to SGEN and left pinning enabled.

My ObjC code wraps a MonoObject * in an NSObject.
When the MonoObject is set it is pinned.
A simple monoObjectTrace property watches to see if the MonoObject moves.

Under the Boehm collector objects seem to stay pinned as requested.
Under SGEN they don’t i.e.: the exception in the second method below raises i.e.:  self.monoObjectTrace != (NSUInteger)monoObject) 

What am I doing wrong?

I do want to migrate to moveable memory support ASAP but a step wise approach seems best.


- (void)setMonoObject:(MonoObject *)monoObject
    if (_mono_gchandle) {
        NSLog(@"calling mono_gchandle_free!");
        _mono_gchandle = 0;
    // we don't want to persist the monoObject in an ivar or on the heap in general as it would
    // require always pinning the pointed to MonoObject
    if (monoObject) {
        _mono_gchandle = mono_gchandle_new(monoObject, self.monoEnvironment.pinGCHandles);
    self.monoObjectTrace = (NSUInteger)monoObject;

- (MonoObject *)monoObject
    // This pointer should be valid while it is visible on the unmanaged stack.
    // Dont save it into the heap as it may become invalid if the MonoObject is not pinned
    // and the managed instance gets moved in memory.
    MonoObject *monoObject = mono_gchandle_get_target(_mono_gchandle);
    if (self.monoObjectTrace != (NSUInteger)monoObject) {
        [NSException raise:@"Managed object has moved" format:@"Support for moved managed objects is pending."];
    return monoObject;


More information about the Mono-devel-list mailing list