using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Tesseract.Interop
{
    unsafe static class MarshalHelper
    {
    	public static IntPtr StringToPtr(string value, Encoding encoding)
        {
            var encoder = encoding.GetEncoder();
            var length = encoding.GetByteCount(value);
            
            var encodedValue = new byte[length + 1];
            encoding.GetBytes(value, 0, value.Length, encodedValue, 0);
            var handle = Marshal.AllocHGlobal(new IntPtr(encodedValue.Length));
            Marshal.Copy(encodedValue, 0, handle, encodedValue.Length);
            return handle;
        }

    	        
        public static string PtrToString(IntPtr handle, Encoding encoding)
        {
            var length = StrLength(handle);
            return new String((sbyte*)handle.ToPointer(), 0, length, encoding);
        }

        
        
        
        public static int StrLength(IntPtr handle)
        {
            var ptr = (byte*)handle.ToPointer();
            int length = 0;
            while (*(ptr + length) != 0) {
                length++;
            }
            return length;
        }


    }
}

