[System.Security.SecurityCritical] // auto-generated static internal unsafe string ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { uint length = Win32Native.SysStringByteLen(bstr); // Intentionally checking the number of bytes not characters to match the behavior // of ML marshalers. This prevents roundtripping of very large strings as the check // in the managed->native direction is done on String length but considering that // it's completely moot on 32-bit and not expected to be important on 64-bit either, // the ability to catch random garbage in the BSTR's length field outweighs this // restriction. If an ordinary null-terminated string is passed instead of a BSTR, // chances are that the length field - possibly being unallocated memory - contains // a heap fill pattern that will have the highest bit set, caught by the check. StubHelpers.CheckStringLength(length); string ret = new String((char*)bstr, 0, (int)(length / 2)); if ((length & 1) == 1) { // odd-sized strings need to have the trailing byte saved in their [....] block ret.SetTrailByte(((byte *)bstr.ToPointer())[length - 1]); } return ret; } }