简体   繁体   中英

How to pass string parameter to c# method using mono embedded?

I want to pass a string parameter to c# method using mono embedded. Here's c# method:

public static void CallMe(string value)
{
    Console.WriteLine(value);
}

Here's c++ call:

PVOID method = mono_class_get_method_from_name(Class, string("CallMe").c_str(), 1);
mono_runtime_invoke(method, NULL, new void*[1] { (void*)"Hello World!\0" }, NULL); 

The printed value is either empty string or question marks. How do i solve this problem?

You must first convert your string in to a MonoString using mono_string_new .

If you are passing value types you need to pass a pointer (string is a pointer already).

Remember to set param_count in mono_class_get_method_from_name to the number of parameters in your C# method.

C++:

void RunMonoMethodWithParams(MonoDomain* domain, PCHAR _namespace, PCHAR _class, PCHAR _method, PCHAR param1)
{
    .
    .
    .
    //Open assembly, get image, class from name...
    .
    .
    .

    PVOID method = mono_class_get_method_from_name(_class, _method, 2);
    
    int param0 = 0xFF;

    //Each index equals 1 parameter
    PVOID args[2];
    args[0] = &param0;
    args[1] = mono_string_new(domain, param1);

    mono_runtime_invoke(method, NULL, args, NULL);
}

C#:

public static int CSharpMethod(int param0, string param1)
{
    ...
}

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