title: Japanese to Romaji with Kakasi
body: <p>I want to transliterate Japanese to Romaji with <a href="http://kakasi.namazu.org/index.html.en" rel="nofollow">Kakasi</a> tool, using C#. For this, I created a wrapper:</p>
  
  <pre><code>    [DllImport("kakasi.dll")]
      static extern int kakasi_getopt_argv(int size, IntPtr param);
      [DllImport("kakasi.dll")]
      static extern IntPtr kakasi_do([MarshalAs(UnmanagedType.LPStr)]string str);
  
      public static void SetParams(string [] paramz)
      {
          kakasi_getopt_argv(paramz.Length, StringToIntPtr(paramz));
      }
  
      public static string DoKakasi(string japanese)
      {
          return Marshal.PtrToStringAuto(kakasi_do(japanese));
      }
  
      private static IntPtr StringToIntPtr(string[] strings)
      {
          int bytesCount;
          IntPtr ptr = IntPtr.Zero;
          ArrayList stringBytes = new ArrayList();
          foreach (string str in strings)
          {
              stringBytes.AddRange(Encoding.Unicode.GetBytes(str));
              stringBytes.Add((byte)'\0');
          }
          bytesCount = stringBytes.Count;
          try
          {
              ptr = Marshal.AllocHGlobal(bytesCount);
              Marshal.Copy((byte[])stringBytes.ToArray(typeof(byte))
                  , 0
                  , ptr
                  , bytesCount);
              return ptr;
          }
          catch
          {
              if (ptr != IntPtr.Zero)
                  Marshal.FreeHGlobal(ptr);
              throw;
          }
      }
  </code></pre>
  
  <p>And then:</p>
  
  <pre><code>KakasiCs.SetParams(new[] { "kakasi", "-ja", "-ga", "-ka", "-Ea", "-Ka", "-Ha", "-Ja", "-U", "-s",});
  var x = KakasiCs.DoKakasi("さかき");
  </code></pre>
  
  <p>I have 2 problems:</p>
  
  <ol>
  <li>Bad output - I receive no romaji, but something strange: "㼿?Äꈎᅵ鄠".   </li>
  <li>In VS2010 every time I receive a warning with PInvokeStackImbalance exception.  </li>
  </ol>
  
  <p>Any help is appreciated. Thanks.</p>