title: C# DLL from C++ Code - p/invoke - Change values
body: <p>I've got a C# DLL using a lot of "Common" DLLs. Now I'd like to call some of these functions/methods from a C++ Program.</p>
  
  <p>In the C# Code I have a structure like this</p>
  
  <pre class="lang-cs prettyprint-override"><code>[StructLayout(LayoutKind.Sequential)]
  public struct Test
  {
      public string MyTestString;
      public int MyInteger;
  }
  </code></pre>
  
  <p>and a delegate</p>
  
  <pre class="lang-cs prettyprint-override"><code>[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate void CallBackDelegate(Test t);
  </code></pre>
  
  <p>which is being used in a class having the "callback".</p>
  
  <pre><code>_delegate = new CallBackDelegate(this.CallBack);
  
  public void CallBack(Test t)
  {
      Console.WriteLine($"Received string: {t.MyTestString}");
  }
  </code></pre>
  
  <p>In the C++/CLI code I've got the "same" structure too. (C++ Projects are Unicode)</p>
  
  <pre class="lang-cpp prettyprint-override"><code>struct Test
  {
      char *MyTestString;
      int MyInteger;
  };
  </code></pre>
  
  <p>and I export the used function to access the C# code.</p>
  
  <pre><code>__declspec(dllexport) void bridge(Test t);
  </code></pre>
  
  <p>In the function I instantiate a object^ of the C# class and take the delegate as <code>IntPtr</code>.</p>
  
  <pre><code>IntPtr ptr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(csharp-&gt;GetDelegate());
  </code></pre>
  
  <p>After that I call the function and pass a object of the structure as parameter.</p>
  
  <pre><code>//typedef void(*NativeToManaged)(Test t);
  NativeToManaged funcPtr = static_cast&lt;NativeToManaged&gt;(ptr.ToPointer());
  funcPtr(t);
  </code></pre>
  
  <p>In the unmanaged code I allocate memory for the char* and copy/assign a string. <code>"What is happening"</code> as example. (Using the C++/CLI header)</p>
  
  <hr>
  
  <p><strong>Now to the problem:</strong></p>
  
  <p>I receive the structure in the C# code correctly, though trying to set a string or modify the integer on C# side does not change anything on C++ side - I assume the structure is just being copied, though I do not know how I'd pass a reference to the C# code. (Possibly as pointer or by ref ?)</p>
  
  <p>As this is my first time doing this, does anyone by chance know where the issue lies ? The C# code should correctly receive the string[s] and other values and be able to modify them. I've so far not been able to find a solution for this on Google and here.</p>