简体   繁体   中英

mono embedding, get MonoClass* without knowing the namespace

Given the C# sample code below it is quite easy to call the Bar.Work static method from C. All it takes is to obtain a MonoClass* , then get a MonoMethod* from the class and invoke it.

The thing is that in order to get the MonoClass* I need to provide Bar's namespace which in this case is 'sampleApp' to the function as a parameter.

MonoClass *klass = mono_class_from_name(image, "sampleApp", "Bar");

The question is how can I obtain the MonoClass* in C if I don't know Bar 's class namespace. Are there any means to get a list of types inside the assembly from C? I couldn't find any examples in mono's embedding samples.

C# sample

namespace sampleApp 
{

  class Bar {
    public static void Work() {
       Console.WriteLine("Bar.Work called");
    }
  }

  class Program {
    public static void Main(string[] args) {
        Console.WriteLine("Program.Main called");
    } 
  }

}

Calling Bar.Work from C

#include <mono/jit/jit.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/class.h> 
#include <mono/metadata/assembly.h>
#include <mono/metadata/image.h>
#include <mono/metadata/object.h>
#include <mono/metadata/debug-helpers.h>

int main(int argc, char **argv) {

        mono_config_parse(NULL);

        MonoDomain *domain = mono_jit_init_version("app", "v4.0.30319");
        MonoAssembly *assembly = mono_domain_assembly_open(domain, "sampleApp.exe");  
        MonoImage *image = mono_assembly_get_image(assembly);  

        mono_jit_exec(domain, assembly, argc, argv);

        //how can I find Bar class if I don't know that it is under the sampleApp namespace?
        MonoClass *klass = mono_class_from_name(image, "sampleApp", "Bar");

        MonoMethod *method = mono_class_get_method_from_name(klass, "Work", 0);

        void *params[1] = { NULL };
        mono_runtime_invoke(method, NULL, params, NULL); 

        mono_jit_cleanup(domain, assembly);

        return 0;
} 

Afaik, Unity is using fixed functions to solve this (Update(), Start()). These are the functions that unity calls, and all the other functions of the script who get called have to be in this predefined functions.

Thats one of the reasons why script names have to match with class names. They just search the folder and use the script name as class name.

Not the answer you wanted, but i think this is the best solution to this.

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