title: Pass a string as argument from C# to callback function in C++
body: <p>I am writing a C# dll wrapper to wrap a third party C# dll.
  I also need to expose this as Java methods for which I am using an intermediate C++ layer which wraps my C# dll and provides a JNI mechanism to expose the same using java.</p>
  
  <p>However, I am having an issue in passing string as argument to the callback function when its invoked in C++. Here is the code.</p>
  
  <pre><code>#include "stdafx.h"
  #include "JavaInclude.h"
  #include &lt;iostream&gt;
  #using "Class1.netmodule"
  #using &lt;mscorlib.dll&gt;
  
  using namespace std;
  using namespace System;
  
  int CSomeClass::MemberFunction(void* someParam)
  {
      cout&lt;&lt;"Yaay! Callback"&lt;&lt;endl;
      return 0;
  }
  
  static int __clrcall SomeFunction(void* someObject, void* someParam, String^ strArg)
  {
      CSomeClass* o = (CSomeClass*)someObject;
      Console::WriteLine(strArg);
      return o-&gt;MemberFunction(someParam);
  }
  
  JNIEXPORT void JNICALL Java_de_tum_kinect_KinectSpeechInit_initConfig
      (JNIEnv *env, jobject obj)
  {
      array&lt;String^&gt;^ strarray = gcnew array&lt;String^&gt;(5);
      for(int i=0; i&lt;5; i++)
              strarray[i] = String::Concat("Number ",i.ToString());
  
      CSomeClass o;
      void* p = 0;
      CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&amp;o), System::IntPtr(p), strarray);
  }
  </code></pre>
  
  <p>Here is my C# class</p>
  
  <pre><code>using System;
  using System.Runtime.InteropServices;
  
  public class CSharp
  {
      delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg, string strArg);
  
      public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg, String[] pUnmanagedStringArray)
      {
          CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate));
  
          for (int i = 0; i &lt; pUnmanagedStringArray.Length; i++)
          {
              Console.WriteLine(pUnmanagedStringArray[i]);
          }
          string strArg = "Test String";
          int rc = func(Obj, Arg, strArg);
      }
  }
  </code></pre>
  
  <p>When I did <code>Console::WriteLine(strArg);</code> in my C++ dll, it just prints a blank string!
  Would really appreciate if anyone can help me as I am pretty new to all this.</p>
  
  <p>Thanks,
  Deepak</p>