示例#1
0
        /// <summary>
        /// Adds a UTF-8 string field to the current active message. The string is compressed with zlib using the compression level as set by <see cref="CompressionLevel" /> which is <see cref="CompressionLevel.Z_BEST_SPEED"/> by default.
        /// </summary>
        /// <param name="tag">The field tag.</param>
        /// <param name="value">The UTF-8 string field value.</param>
        /// <returns><see langword="true" /> if the field was successfully added, or <see langword="false" /> if the value could not be added (because there was no more memory, the message handle does not contain any messages, or the supplied value is not of the type specified).</returns>
        /// <exception cref="ObjectDisposedException">The <see cref="Message"/> instance has been disposed.</exception>
        /// <remarks>The corresponding native function is mdf_message_add_string.</remarks>
        public bool AddString(uint tag, string value)
        {
            ThrowIfDisposed();
            if (value == null)
            {
                return(_nativeImplementation.mdf_message_add_string(Handle, tag, IntPtr.Zero) == 1);

                fixed(char *c = value)
                {
                    int   length       = Encoding.UTF8.GetMaxByteCount(value.Length);
                    byte *b            = stackalloc byte[length + 1];
                    int   bytesWritten = Encoding.UTF8.GetBytes(c, value.Length, b, length);

                    b[bytesWritten] = 0;
                    return(_nativeImplementation.mdf_message_add_string(Handle, tag, (IntPtr)b) == 1);
                }
        }