I am using libmono to call a C# object from my C code. Some of the methods for that object take Object parameters. So for instance, to call an object with an array parameter, i use
MonoArray *data = mono_array_new(domain, mono_get_byte_class(), len);
and then call mono_runtime_invoke with the object and parameters listed. How do i know that the array isn’t garbage collected in between mono_array_new and mono_runtime_invoke?
As long as you keep the data pointer as a local variable in the function where invoke() is called, it won’t be garbage collected. Or, since it needs to be stored in the argument array for mono_runtime_invoke(), make sure that array is a local variable (stack or register allocated. A function argument is equivalent to a local variable).
If you need to store a managed object in any other place, like a static variable, a thread local, somewhere in malloced memory etc., then you need to keep a reference to it yourself, for example using the mono_gchandle_new() API.