Search code examples
c#c++pointerscomcom-interop

How to pass a String pointer/reference from C++ to C#?


I'm writing a C# com library. I need a function that takes string from C++ and modifies string, after I have modified this string in my library modified value should be usable by C++ code. Here is my function (it's not working),

C# Interface,

Int32 testString([param: MarshalAs(UnmanagedType.LPStr)] ref string strData);

C# Implementation,

class Test:ITest
{
  public int testString(ref string strData)
       {

            strData = strData + strData;
            Console.WriteLine("strData in lib :"+strData);
            return 0;
        }
}

C++ code (I missed the parts, registering com lib, importing tlb etc.),

ITest * mInterface = NULL;
//...initilizing interface , skipped since this parts has no problem
LPSTR tt = "OLA";
mInterface ->testString(&tt); //It crashes when comes here ..
cout << tt <<endl; 

Solution

  • I have found a solution to my problem , I am not sure but maybe we cannot initilized object from c++ to c# using com interop.If a use a null pointer to c# com , and initilize that pointer inside c# library code it worked .You can see the sample below ;

    c# library interface

    int testString(out string val);
    

    c# library imp

    class Test
    {
        int testString(out string val)
        {
            val = "Hello world"; //now user of this method can use val 
            return 0;
        }
    }
    

    c++ usage

    #pragma warning (disable: 4278)
    
    #import "../yourtlb.tlb" no_namespace named_guids
    ITestInterface * fpInterface = NULL;
        int retval = 1;
        CoInitialize(NULL);
    
        HRESULT hr = CoCreateInstance(CLSID_Test ,
                   NULL, CLSCTX_INPROC_SERVER,
                   IID_ITestInterface, reinterpret_cast<void**>(&fpInterface));
    
        if(!FAILED(hr))
        {
            BSTR val = NULL;
            int ret = fpInterface->testString(val);
            cout <<val<<endl;
        }
    

    Of course before using code in c++ , dont forget to generate tlb file from your c# project , and dont forget to edit registry files.Here you can see a good sample