Search code examples
c#c++-cli

How to give the parameter to C#'s function from C++?


Caller: C++ code
Callee: C# code

C# Code:

public int CSharpMethodName(string str, params object[] args)
{
   ....
}

C++ Code:

bool CPPMethodName(const CString& cstr, CString parameters[])
{
      //The object is already initialized with gcroot in order to access to C# code. 

     //Here I want to give parameters to the CSharpMethodName
     result = obj->CSharpMethodName(gcnew System::String(sqlQuery), parameters);
}

This is the signature for C# method when added to the C++ project as a reference: CSharpMethodName(System::String^, ... array<System::Object^>^)

How can I give the CString array type of the parameters to the CSharp method? Please let me know if anything is not clear.

Thanks


Solution

  • I found out that I have to convert unmanaged array to managed array.

    Here is the complete code that works for me:

    bool CPPMethodName(const CString& cstr, const CString parameters[], size_t size)
    {
          cli::array<System::String^>^ managedParametersArray = GetManagedArray(parameters, size);
          result = obj->CSharpMethodName(gcnew System::String(sqlQuery), managedParametersArray );
    
          return result;
    }
    
    cli::array<System::String^>^ AdoHelperWrapper::GetManagedArray(const CString paramaters[], size_t size)
    {
        cli::array<System::String^>^ result = gcnew cli::array<System::String^>(size);
    
        for (size_t i = 0; i < size; i++)
        {
            result[i] = gcnew System::String(paramaters[i]);
        }
        return result;
    }