Esempio n. 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AnsiStringMarshaller"/>.
        /// </summary>
        /// <param name="str">The string to marshal.</param>
        /// <param name="buffer">Buffer that may be used for marshalling.</param>
        /// <remarks>
        /// The <paramref name="buffer"/> must not be movable - that is, it should not be
        /// on the managed heap or it should be pinned.
        /// <seealso cref="CustomTypeMarshallerFeatures.CallerAllocatedBuffer"/>
        /// </remarks>
        public AnsiStringMarshaller(string?str, Span <byte> buffer)
        {
            _allocated = null;
            if (str is null)
            {
                _span = default;
                return;
            }

            // + 1 for null terminator
            int maxByteCount = (str.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1;

            if (buffer.Length >= maxByteCount)
            {
                Marshal.StringToAnsiString(str, (byte *)Unsafe.AsPointer(ref MemoryMarshal.GetReference(buffer)), buffer.Length);
                _span = buffer;
            }
            else
            {
                _allocated = (byte *)Marshal.StringToCoTaskMemAnsi(str);
                _span      = default;
            }
        }