简体   繁体   中英

Embedded Mono: Keeping references to C# objects in C++

I'm working on embedding mono into an application I'm creating, and I haven't gotten super far, but one of the things I can't seem to find is how to tell mono when I'm using an object and done with an object.

I want to keep a reference to a C# object to call methods on until the lifetime of it's parallel object in C++ is over, at which point, I want to tell mono that the C# object is safe to collect.

How is this accomplished?

It appears that what I'm looking for is mono_gchandle_new , and hold onto the handle, not the MonoObject*, and use mono_gchandle_get_target when I need it.

mono_gchandle_new allows you to pin when creating the handle, but is it possible to pin after the fact?

One thing to keep in mind when using mono_gchandle_new() that I encountered.. it will keep only the C# object you referenced in memory, but if that object allocates other objects those are still subject to the garbage collection routines. The fact that a object you have a handle for, can have it's sub-objects freed on you has caused me quite a bit of trouble.

I'm currently digging through the mono GC system to see if I can fix it so it will treat those objects as root objects.

If you have few enough objects (<4096), you can use mono_gc_register_root()... we can have thousands of objects, so this is no good for our uses.

UPDATE: So I was incorrect about this, we had hooked into the mono object allocation system and we weren't passing through the "atomic" variable correctly onto the GC allocation functions. "Atomic" means something different to the GC, it doesn't have anything to do with concurrent access, it actually means the memory being allocated references other objects (atomic=0) or not (atomic=1).

Use System::GCHandle::Alloc and call ToIntPtr on the result to get a token and protect the object from collection. Call ToPointer() and store as a void* .

Use System::GCHandle::FromIntPtr when you need to map the token to the object, or release it so it is again eligible for collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM