Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>GCHandle.Alloc</code> <a href="http://msdn.microsoft.com/en-us/library/a95009h1.aspx" rel="nofollow noreferrer"><em>"Allocates a Normal handle for the specified object"</em></a>, which <em>"creates a handle to a managed object ... which prevents the managed object from being collected"</em>.</p> <p>What you're looking for is the methods from <code>System.Runtime.InteropServices.Marshal</code>, which allow you to do things like copy managed objects to memory accessible by unmanaged code. Unfortunately, according to <a href="http://msdn.microsoft.com/en-us/library/0szztey7%28VS.80%29.aspx" rel="nofollow noreferrer">this</a>, the pointers in your struct make it a little harder to marshal than many other things (in the sense that many other things can be automatically marshalled using the appropriate P/Invoke attributes), but it's still possible. I've tried this out and it works:</p> <pre><code>APP_PARAM param = new APP_PARAM(); string[] text = new string[] { "A", "B", "C" }; param.numData = text.Length; // Manually allocate an array of pointers, one for each string. arr holds the array's address. IntPtr arr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * text.Length); try { param.text = arr; IntPtr[] unmanagedText = new IntPtr[text.Length]; try { // Create a null-terminated ANSI string in unmanaged memory for each element in text. for (int i = 0; i &lt; text.Length; i++) unmanagedText[i] = Marshal.StringToHGlobalAnsi(text[i]); // Copy the addresses of the unmanaged strings into the manually allocated array. // I don't know of any way to make an unmanaged copy of a managed array in one call. Marshal.Copy(unmanagedText, 0, arr, unmanagedText.Length); // param now looks like what the C++ code is expecting (except for the array of int). StartApp(param); } finally { foreach (IntPtr str in unmanagedText) Marshal.FreeHGlobal(str); } } finally { Marshal.FreeHGlobal(arr); } </code></pre> <p>You'll have to have similar allocation/free code for your array of int values, with its own try/finally blocks to make sure FreeHGlobal is called.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload