Lifetime of the object returned from mono_runtime_invoke

Viewed 21

Suppose that I have a C# method that produces some data:

public class Producer {
    public byte[] GetSomeData(int length) {
        byte[] result = new byte[length];
        // Fill some data;
        return result;
    }
}

Now I'd like to consume the data from native side. It is possible to call a managed method and retrieve its return value via mono embedding API:

extern MonoMethod* GetSomeDataMethod;
extern MonoObject* producerObject;

void process_data(int length) {
    void* args[1] = { &length };
    MonoArray* data = (MonoArray*)mono_runtime_invoke(GetSomeDataMethod, producerObject, args, NULL);
    // Process the returned data
}

The question is:

  1. Who is responsible for managing the lifetime of the returned MonoArray* data?
    I didn't find any API to "release" a MonoObject reference, so I assume that everything is managed by mono runtime and the lifetime of the returned object is tracked by GC.
  2. This leads to the second question: how long will the returned object remain valid?
    To what extent it is safe to access the returned data freely from native code, and at what time will the garbage collector kick in?
  3. And the third: how can I tell the runtime that the returned object is still in use, and how can I notify the runtime that the native code has done its business with that object?
    It will be bad if the object is suddenly invalidated by GC while native code is still doing some (slow) work on it. And it will be equally bad if any leakage happens.
0 Answers
Related