mercredi 8 janvier 2020

Calling C# function with out parameter from C++ - COM interop/reflection

I currently working on a system that must take C# assembly, and execute the specified function from unmanaged C++ - and update a string passed from C++ by reference. To give an example, let us say I had the following C#.

class Foo
{
    public Int32 Bar(string output)
    {
        Console.WriteLine(output);
        return 0;
    }
}

In C++, after setting up my parameters by putting them in a SAFEARRAY (args in the example below), I can call this function with something like:

variant_t rv;
bstr_t func_name(L"Bar");
auto bindingFlags = ...; // mscorlib::BindingFlags_InvokeMethod, etc.
auto inst = ...; // A `variant_t` from a call to `CreateInstance(...)`

// `x` is an `mscorlib::_TypePtr` from a call to `GetInterface(...)`
x->InvokeMember_3(func_name, bindingFlags, nullptr, inst, args, &rv)

This seems to work fine, and the string "hello world" can successfully be passed to the C# method from C++. However, I am uncertain how to pass the string by reference from C++ to C#, and allow C# to modify the data that was created in the unmanaged C++.

For example, something like:

class Foo
{
    public Int32 Bar(out string output)
    {
        output = "hello world"
        return 0;
    }
}

When this is called from C++, I'd like to have a char* updated to contain the string "hello world".

I can still call the method just fine, but the string remains empty in C++ after execution, even if I pass it by reference from C++.

I suspect that it has something to do with how C++ handles pointers compared to C#, and perhaps there is not straightforward answer to this. Any help would be greatly appreciated!

(Sorry for my english, it is not my first language)





Aucun commentaire:

Enregistrer un commentaire