1

The goal is this: call methods of the .NET library from unamanged c++ using late binding without using COM and import tlb library.

I have a trivial class written in c# (just for test) put in a class library (CSLib) compiled with framework 4.0

public class MyCSObject { string _str = "Test";

    public int GetString(out string str)
    {
        str = _str;
        return 0;
    }

    public int PutString(string str)
    {
        _str = str;
        return 0;
    }

}

I've created the trivial cpp application that i listed here:

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include <metahost.h>
#pragma comment(lib, "mscoree.lib")

// Import mscorlib.tlb (Microsoft Common Language Runtime Class Library).
#import "mscorlib.tlb" raw_interfaces_only              \
 high_property_prefixes("_get","_put","_putref")        \
 rename("ReportEvent", "InteropServices_ReportEvent")
using namespace mscorlib;
#pragma endregion

int main()
{
HRESULT hr;

ICLRMetaHost *pMetaHost = NULL;
ICLRRuntimeInfo *pRuntimeInfo = NULL;

// ICorRuntimeHost and ICLRRuntimeHost are the two CLR hosting interfaces
// supported by CLR 4.0. Here we demo the ICorRuntimeHost interface that 
// was provided in .NET v1.x, and is compatible with all .NET Frameworks. 
ICorRuntimeHost *pCorRuntimeHost = NULL;

IUnknownPtr spAppDomainThunk = NULL;
_AppDomainPtr spDefaultAppDomain = NULL;

// The .NET assembly to load.
bstr_t bstrAssemblyName(L"CSLib");
_AssemblyPtr spAssembly = NULL;

// The .NET class to instantiate.
bstr_t bstrClassName(L"CSLib.MyCSObject" );
_TypePtr spType = NULL;
variant_t vtObject;
variant_t vtEmpty;

// The instance method in the .NET class to invoke.
bstr_t bstrMethodNameGet(L"GetString");
bstr_t bstrMethodNamePut(L"PutString");

bstr_t bstrparam(L"Helloworld");
variant_t vtRet;

SAFEARRAY *psaMethodArgs = NULL;
variant_t vtStringRet;

// 
// Load and start the .NET runtime.
// 

wprintf(L"Load and start the .NET runtime %s \n", L"v4.0.30319");

hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));

hr = pRuntimeInfo->GetInterface(CLSID_CorRuntimeHost,
    IID_PPV_ARGS(&pCorRuntimeHost));

hr = pCorRuntimeHost->Start();
// Get a pointer to the default AppDomain in the CLR.
hr = pCorRuntimeHost->GetDefaultDomain(&spAppDomainThunk);
hr = spAppDomainThunk->QueryInterface(IID_PPV_ARGS(&spDefaultAppDomain));


// Load the .NET assembly.
hr = spDefaultAppDomain->Load_2(bstrAssemblyName, &spAssembly);

// Get the Type of CSSimpleObject.
hr = spAssembly->GetType_2(bstrClassName, &spType);

// Instantiate the class.
hr = spAssembly->CreateInstance(bstrClassName, &vtObject);

// Call the instance method of the class.
//   public string ToString();

// Create a safe array to contain the arguments of the method.
psaMethodArgs = SafeArrayCreateVector(VT_VARIANT, 0, 1);
VARIANT vtpar;
vtpar.vt = VT_BSTR;
vtpar.bstrVal = bstrparam;
long r = 0;
hr = SafeArrayPutElement(psaMethodArgs, &r, &vtpar);

// Invoke the "ToString" method from the Type interface.
hr = spType->InvokeMember(bstrMethodNamePut, 
                        static_cast<BindingFlags>( BindingFlags_InvokeMethod | BindingFlags_Instance | BindingFlags_Public),
                        NULL, 
                        vtObject, 
                        psaMethodArgs, 
                        NULL, 
                        NULL, 
                        NULL,
                        &vtRet);


BSTR bstr(_T(""));
SAFEARRAY* psaMethodArgsByRef = SafeArrayCreateVector(VT_VARIANT , 0, 1);
VARIANT vtbstr;
vtbstr.vt = VT_BSTR | VT_BYREF;
vtbstr.pbstrVal = &bstr;
r = 0;
hr  = SafeArrayPutElement(psaMethodArgsByRef, 0, &vtbstr);

SAFEARRAY* modifiers = NULL;

// VARIANT WITH INSDE VARIANT_BOOL
/*modifiers = SafeArrayCreateVector(VT_VARIANT, 0, 1);
VARIANT vtmod;
vtmod.vt = VT_BOOL;
vtmod.boolVal = VARIANT_TRUE;
hr  = SafeArrayPutElement(psaMethodArgsByRef, 0, &vtmod);*/

// VARIANT_BOOL
/*modifiers = SafeArrayCreateVector(VT_BOOL, 0, 1);
VARIANT_BOOL bmod = VARIANT_TRUE;
hr = SafeArrayPutElement(psaMethodArgsByRef, 0, &bmod);*/





hr = spType->InvokeMember(bstrMethodNameGet,
    static_cast<BindingFlags>(BindingFlags_InvokeMethod | BindingFlags_Instance | BindingFlags_Public),
    NULL,
    vtObject,
    psaMethodArgsByRef,
    modifiers,
    NULL,
    NULL,
    &vtRet);



return 0;
}

Everything works fine if C++ application calls methods that have only input parameters like 'PutString', but doesn't work when it calls methods that has out or ref parameters like 'GetString' of my library.

I think the problem is the method of the mscorelibrary InvokeMethod

virtual HRESULT __stdcall InvokeMember (
    /*[in]*/ BSTR name,
    /*[in]*/ enum BindingFlags invokeAttr,
    /*[in]*/ struct _Binder * Binder,
    /*[in]*/ VARIANT Target,
    /*[in]*/ SAFEARRAY * args,
    /*[in]*/ SAFEARRAY * modifiers,
    /*[in]*/ struct _CultureInfo * culture,
    /*[in]*/ SAFEARRAY * namedParameters,
    /*[out,retval]*/ VARIANT * pRetVal ) = 0;   

and in particular in SAFEARRAY modifiers parameter: I have no idea to set this parameter I try different solution (like ones I've commented in my code) and I did not found any documentation about this when I call this method from unmanaged c++.

Alessandro Ciurlo
  • 102
  • 1
  • 2
  • 11
  • 2
    This was asked before, nobody ever posts an unhelpful answer. The CLR goes through the trouble of converting the argument back to a VARIANT after the call but only does so when it has the [Out] attribute. – Hans Passant Apr 20 '17 at 15:29
  • Do you mean that this way to calling method works only when the parameter of the .NET method is marked as an [out] parameter? However I was unable to do this too...Maybe I do something wrong passing the modifier parameter? – Alessandro Ciurlo Apr 20 '17 at 16:02

0 Answers0