title: How can I copy a array of strings into an unmanaged char double pointer?
body: <p>I have a <code>char**</code> in a C struct which is allocated in the C code as a <strong>Nx128</strong> matrix. In C# I have an array of strings and I want to copy this array to the char double pointer, without reallocating anything. I tried this:</p>
  
  <pre><code>public void StringArrayToPtr(IntPtr ptr, string[] array) 
  {
  
      for (int i = 0; i &lt; array.Length; i++)
      {
          char[] chars = (array[i] + '\0').ToCharArray();
  
          Marshal.Copy(chars, 0, IntPtr.Add(ptr, 128*i), chars.Length);
      }
  }
  </code></pre>
  
  <p>But this doesn't work. <strong>Does somebody know how to perform such a copy ?</strong></p>
  
  <p>UPDATE:</p>
  
  <p>Here is how my <code>char** names</code> is allocated in the C code for 3 items: <code>names = (char **) MallocArray2D (3, 128, sizeof ( char ));</code></p>
  
  <p>Here is the details of the <code>MallocArray2D</code> method:</p>
  
  <pre><code>void ** MallocArray2D (
       int  n1,
       int  n2,
       int  size_elem )
  {
      void ** p2;
      void * p1;
      size_t i;
  
      p1 = (void *) malloc (size_elem * n1 * n2); 
  
      p2 = (void **) malloc (n1 * sizeof ( void * ));
  
  
      for ( i = 0 ; i &lt; n1 ; i++ )
      {
          p2[i] = (char *) p1 + size_elem * n2 * i;
      }
  
      return p2;
  }
  </code></pre>
  
  <p>This <code>MallocArray2D</code> method is called into a <code>MallocImage</code> which is exposed in my C# code.</p>
  
  <p>Here is the <code>MallocImage</code> method interesting part in C code:</p>
  
  <pre><code>int MallocImage (
       IMAGE *  image,
       int           nxyz,
       int           nvar )
  {
      //... Allocating others objects
  
      image-&gt;names = (char **) MPDSMallocArray2D ( nvar, 128, sizeof ( char ));
  
  }
  </code></pre>
  
  <p>Now my C# exposed <code>MallocImage</code> method:</p>
  
  <pre><code>[DllImport(DLL_PATH, CallingConvention = CallingConvention.Cdecl)]
  public static extern int MallocImage([In, Out]Image image, int nXYZ, int nVar);
  
  // My Image class
  [StructLayout(LayoutKind.Sequential)]
  class Image {
  
      private IntPtr names;
  
      public string[] Names {
  
          set {ArrayOfStringToPtr(names, value);}
  
      }
  
      // Constructor
      public Image(int nVar, int nXYZ) {
  
          MallocImage(this, nXYZ, nVar);
  
      }
  
  }
  
  
  // Somewhere else in my code
  image.Names = new string[] {"porosity", "duplicity", "facies"];
  </code></pre>