Exemple #1
0
        public static unsafe IntPtr StringToCoTaskMemAnsi(string s)
        {
            if (s == null)
            {
                return(IntPtr.Zero);
            }

            long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
            int  nb  = (int)lnb;

            // Overflow checking
            if (nb != lnb)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));

            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            s.ConvertToAnsi((byte *)hglobal, nb, false, false);
            return(hglobal);
        }
Exemple #2
0
        public static unsafe IntPtr StringToCoTaskMemUni(string s)
        {
            if (s == null)
            {
                return(IntPtr.Zero);
            }

            int nb = (s.Length + 1) * 2;

            // Overflow checking
            if (nb < s.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));

            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            fixed(char *firstChar = s)
            {
                string.wstrcpy((char *)hglobal, firstChar, s.Length + 1);
            }

            return(hglobal);
        }
Exemple #3
0
        public static unsafe IntPtr StringToCoTaskMemUTF8(string s)
        {
            if (s == null)
            {
                return(IntPtr.Zero);
            }

            int    nb   = Encoding.UTF8.GetMaxByteCount(s.Length);
            IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1));

            if (pMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            fixed(char *firstChar = s)
            {
                byte *pbMem     = (byte *)pMem;
                int   nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);

                pbMem[nbWritten] = 0;
            }

            return(pMem);
        }
Exemple #4
0
        public static IntPtr AllocCoTaskMem(int cb)
        {
            IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));

            if (pNewMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return(pNewMem);
        }