Example #1
0
        /// <summary>
        /// 指定されたメモリブロックの内容を、他の場所へコピーします。
        /// </summary>
        /// <param name="outDest"></param>
        /// <param name="inSrc"></param>
        /// <param name="inNumOfBytes"></param>
        /// <remarks>
        /// Yanesdk.NET (http://yanesdkdotnet.sourceforge.jp/) の Screen2DGl.cs から借用させて頂きました。
        /// </remarks>
#else
        /// <summary>
        /// 
        /// </summary>
        /// <param name="outDest"></param>
        /// <param name="inSrc"></param>
        /// <param name="inNumOfBytes"></param>
#endif
        public static unsafe void CopyMemory(void* outDest, void* inSrc, uint inNumOfBytes)
        {
#if net20 || net40
            // 転送先をuint幅にalignする
            const uint align = sizeof(uint) - 1;
            uint offset = (uint)outDest & align;
            // ↑ポインタは32bitとは限らないので本来このキャストはuintではダメだが、
            // 今は下位2bitだけあればいいのでこれでOK。
            if (offset != 0)
                offset = align - offset;
            offset = Math.Min(offset, inNumOfBytes);

            // 先頭の余り部分をbyteでちまちまコピー
            byte* srcBytes = (byte*)inSrc;
            byte* dstBytes = (byte*)outDest;
            for (uint i = 0; i < offset; i++)
                dstBytes[i] = srcBytes[i];

            // uintで一気に転送
            uint* dst = (uint*)((byte*)outDest + offset);
            uint* src = (uint*)((byte*)inSrc + offset);
            uint numOfUInt = (inNumOfBytes - offset) / sizeof(uint);
            for (uint i = 0; i < numOfUInt; i++)
                dst[i] = src[i];

            // 末尾の余り部分をbyteでちまちまコピー
            for (uint i = offset + numOfUInt * sizeof(uint); i < inNumOfBytes; i++)
                dstBytes[i] = srcBytes[i];
#else
            Buffer.MemoryCopy(inSrc, outDest, inNumOfBytes, inNumOfBytes);
#endif
        }
Example #2
0
        public static unsafe void* AllocateObject(void* methodTable, uint classSize)
        {
            // HACK: Add compiler architecture to the runtime
            uint nativeIntSize = 4;

            //
            // An object has the following memory layout:
            //   - IntPtr MTable
            //   - IntPtr SyncBlock
            //   - 0 .. n object data fields
            //
            ulong allocationSize = (ulong)((2 * nativeIntSize) + classSize);

            void* memory = MemoryPageManager.Allocate(IntPtr.Zero, allocationSize, PageProtectionFlags.Read | PageProtectionFlags.Write | PageProtectionFlags.WriteCombine).ToPointer();
            if (memory == null)
            {
                throw new OutOfMemoryException();
            }

            uint* destination = (uint*)memory;
            Memset((byte*)destination, 0, (int)allocationSize);
            destination[0] = (uint)methodTable;
            destination[1] = 0; // No sync block initially

            return memory;
        }
Example #3
0
        /// <summary>
        /// Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.
        /// </summary>
        /// <param name="dwFlags">
        /// The formatting options, and how to interpret the lpSource parameter. The low-order byte of dwFlags specifies how the function handles line breaks in the output buffer. The low-order byte can also specify the maximum width of a formatted output line.
        /// The <see cref="FormatMessageFlags.FORMAT_MESSAGE_ARGUMENT_ARRAY"/> flag is always added
        /// and the <see cref="FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER"/> flag is always suppressed by this helper method
        /// </param>
        /// <param name="lpSource">
        /// The location of the message definition. The type of this parameter depends upon the settings in the <paramref name="dwFlags"/> parameter.
        /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_HMODULE"/>: A handle to the module that contains the message table to search.
        /// If <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>: Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly.
        /// If neither of these flags is set in dwFlags, then lpSource is ignored.
        /// </param>
        /// <param name="dwMessageId">
        /// The message identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING" />.
        /// </param>
        /// <param name="dwLanguageId">
        /// The language identifier for the requested message. This parameter is ignored if dwFlags includes <see cref="FormatMessageFlags.FORMAT_MESSAGE_FROM_STRING"/>.
        /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order:
        /// Language neutral
        /// Thread LANGID, based on the thread's locale value
        /// User default LANGID, based on the user's default locale value
        /// System default LANGID, based on the system default locale value
        /// US English
        /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND.
        /// </param>
        /// <param name="Arguments">
        /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on.
        /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string.
        /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start.
        /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array.
        /// </param>
        /// <param name="maxAllowedBufferSize">The maximum size of the returned string. If exceeded, <c>null</c> is returned.</param>
        /// <returns>
        /// If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character.
        /// If the function fails, the return value is zero. To get extended error information, call <see cref="GetLastError"/>.
        /// </returns>
        public static unsafe string FormatMessage(FormatMessageFlags dwFlags, void* lpSource, int dwMessageId, int dwLanguageId, IntPtr[] Arguments, int maxAllowedBufferSize)
        {
            string errorMsg;

            StringBuilder sb = new StringBuilder(256);
            do
            {
                if (TryGetErrorMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, sb, Arguments, out errorMsg))
                {
                    return errorMsg;
                }
                else
                {
                    if (GetLastError() == Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER)
                    {
                        // increase the capacity of the StringBuilder by 4 times.
                        sb.Capacity *= 4;
                    }
                    else
                    {
                        // No message with the given ID was found, or some other error occurred.
                        return null;
                    }
                }
            }
            while (sb.Capacity < maxAllowedBufferSize);

            // If you come here then a size as large as 65K is also not sufficient.
            return null;
        }
Example #4
0
 public static void* BoxBoolean(void* methodTable, uint classSize, bool value)
 {
     byte* memory = (byte*)AllocateObject(methodTable, classSize);
     bool* destination = (bool*)(memory + (nativeIntSize * 2));
     destination[0] = value;
     return memory;
 }
Example #5
0
        private void OnLogCallback(void* data, libvlc_log_level level, char* fmt, char* args)
        {
            try
            {
                char* buffer = stackalloc char[BUFFER_SIZE];
                int len = vsprintf(buffer, fmt, args);
                string msg = Marshal.PtrToStringAnsi(new IntPtr(buffer), len);

                switch (level)
                {
                    case libvlc_log_level.LIBVLC_DEBUG:
                        m_logger.Debug(msg);
                        break;
                    case libvlc_log_level.LIBVLC_NOTICE:
                        m_logger.Info(msg);
                        break;
                    case libvlc_log_level.LIBVLC_WARNING:
                        m_logger.Warning(msg);
                        break;
                    case libvlc_log_level.LIBVLC_ERROR:
                    default:
                        m_logger.Error(msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                m_logger.Error("Failed to handle log callback, reason : " + ex.Message);
            }
        }
Example #6
0
		unsafe public ArgIterator (RuntimeArgumentHandle arglist, void *ptr)
		{
			sig = IntPtr.Zero;
			args = IntPtr.Zero;
			next_arg = num_args = 0;
			Setup (arglist.args, (IntPtr) ptr);
		}
Example #7
0
 protected uint GetProperty(string pszProperty, void* pbOutput, uint cbOutput)
 {
     uint retVal;
     int ntstatus = UnsafeNativeMethods.BCryptGetProperty(this, pszProperty, pbOutput, cbOutput, out retVal, dwFlags: 0);
     UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus);
     return retVal;
 }
 public static void BlockCopy(void* from, void* to, uint byteCount)
 {
     if (byteCount != 0)
     {
         BlockCopyCore((byte*)from, (byte*)to, byteCount);
     }
 }
Example #9
0
		public static int Read7BitInt (void* ptr, int* ret_len)
		{
			// Originally from Mono: mcs/class/corlib/System.IO/BinaryReader.cs
			// Copyright (C) 2004 Novell

			int ret = 0;
			int shift = 0;
			byte* bp = (byte*) ptr;
			byte b;

			do {
				b = *bp;
				++bp;

				if (ret_len != null)
					(*ret_len)++;

				ret = ret | (((int) (b & 0x7f)) << shift);
				shift += 7;
			} while ((b & 0x80) == 0x80);

#if VERBOSE_BinaryTool
			TextMode.WriteLine ("read7bit: ", ret);
#endif

			return ret;
		}
Example #10
0
 public static void Append(uint* srcIn, ref void* dst)
 {
     int count = sizeof(uint*);
     void* src = &srcIn;
     Copy(src, dst, count);
     dst = (void*)((int)dst + count);
 }
Example #11
0
 public static void* BoxInt16(void* methodTable, uint classSize, short value)
 {
     byte* memory = (byte*)AllocateObject(methodTable, classSize);
     short* destination = (short*)(memory + (nativeIntSize * 2));
     destination[0] = value;
     return memory;
 }
 private unsafe int DirectInputEnumCreatedEffectsImpl(void* deviceInstance, IntPtr data)
 {
     var newEffect = new Effect((IntPtr)deviceInstance);
     Effects.Add(newEffect);
     // Return true to continue iterating
     return 1;
 }
Example #13
0
		internal unsafe TextInfo (CultureInfo ci, int lcid, void* data, bool read_only)
		{
			this.m_isReadOnly = read_only;
			this.m_win32LangID = lcid;
			this.ci = ci;
			if (data != null)
				this.data = *(Data*) data;
			else {
				this.data = new Data ();
				this.data.list_sep = (byte) ',';
			}

			CultureInfo tmp = ci;
			while (tmp.Parent != null && tmp.Parent.LCID != 0x7F && tmp.Parent != tmp)
				tmp = tmp.Parent;

			if (tmp != null) {
				switch (tmp.LCID) {
				case 44: // Azeri (az)
				case 31: // Turkish (tr)
					handleDotI = true;
					break;
				}
			}
		}
 /// <summary>
 ///     计算32位Hash值
 /// </summary>
 /// <param name="data">数据起始位置</param>
 /// <param name="length">数据长度</param>
 /// <returns>32位HASH值</returns>
 internal static unsafe int GetHashCode(void* data, int length)
 {
     if (PubPlus.MemoryBits == 64)
     {
         var value = GetHashCode64((byte*) data, length);
         return (int) (value ^ (value >> 32));
     }
     //  一般编码都以字节为基本单位,也就是说基本单位长度为8bit;
     //  常用编码可能比较集中,造成编码中出现伪固定位(大多时候某些固定位都是同一值)
     //  采用移位的方式:当移位量为1或7时,一般只能覆盖掉1个固定位;当移位量为3或5时,一般能覆盖掉3个固定位;所以本程序使用的移位量为8x+5/3
     //  由于64=5+59=13+3*17=3*7+43=29+5*7=37+3*3*3=5*9+19=53+11=61+3,其中(5+59),(53+11),(61+3)为素数对成为最佳移位量,本程序选择中性素数对53+11
     //  由于32=5+3*3*3=13+19=3*7+11=29+3,其中(13+19),(29+3)为素数对成为最佳移位量,本程序选择中性素数对13+19
     if (length >= sizeof (uint))
     {
         var value = *(uint*) data;
         var start = (byte*) data;
         for (var end = start + (length & (int.MaxValue - sizeof (uint) + 1));
             (start += sizeof (uint)) != end;
             value ^= *(uint*) start)
         {
             value = (value << 13) | (value >> 19);
         }
         if ((length & (sizeof (uint) - 1)) != 0)
         {
             value = (value << 13) | (value >> 19);
             value ^= *(uint*) start << ((sizeof (uint) - (length & (sizeof (uint) - 1))) << 3);
         }
         return (int) value ^ length;
     }
     return (int) (*(uint*) data << ((sizeof (uint) - length) << 3)) ^ length;
 }
Example #15
0
        private unsafe static void MyHandleCleanFunc(void* a)
        {
            GCHandle gch = GCHandle.FromIntPtr((IntPtr)a);
            BinaryReader br = (BinaryReader)gch.Target;

            br.Close();
        }
        private unsafe int OnFormatCallback(void** opaque, char* chroma, int* width, int* height, int* pitches, int* lines)
        {
            IntPtr pChroma = new IntPtr(chroma);
            string chromaStr = Marshal.PtrToStringAnsi(pChroma);

            ChromaType type;
            if (!Enum.TryParse<ChromaType>(chromaStr, out type))
            {
                throw new ArgumentException("Unsupported chroma type " + chromaStr);
            }

            m_format = new BitmapFormat(*width, *height, type);
            if (m_formatSetupCB != null)
            {
                m_format = m_formatSetupCB(m_format);              
            }

            Marshal.Copy(m_format.Chroma.ToUtf8(), 0, pChroma, 4);
            *width = m_format.Width;
            *height = m_format.Height;
    
            for (int i = 0; i < m_format.Planes; i++)
            {
                pitches[i] = m_format.Pitches[i];
                lines[i] = m_format.Lines[i];
            }

            m_pixelData = new PlanarPixelData(m_format.PlaneSizes);

            return m_format.Planes;
        }
Example #17
0
        private void OnLogCallback(void* data, LibvlcLogLevel level, void* ctx, char* fmt, char* args)
        {
            try
            {
                char* buffer = stackalloc char[BufferSize];
                var len = vsprintf(buffer, fmt, args);
                var msg = Marshal.PtrToStringAnsi(new IntPtr(buffer), len);

                switch (level)
                {
                    case LibvlcLogLevel.LibvlcDebug:
                        _mLogger.Debug(msg);
                        break;
                    case LibvlcLogLevel.LibvlcNotice:
                        _mLogger.Info(msg);
                        break;
                    case LibvlcLogLevel.LibvlcWarning:
                        _mLogger.Warning(msg);
                        break;
                    case LibvlcLogLevel.LibvlcError:
                    default:
                        _mLogger.Error(msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                _mLogger.Error("Failed to handle log callback, reason : " + ex.Message);
            }
        }
Example #18
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="ctx">Context.</param>
 /// <param name="target">Target.</param>
 public UnmanagedTarget(UnmanagedContext ctx, void* target)
     : base(IntPtr.Zero)
 {
     _ctx = ctx;
     
     SetHandle(new IntPtr(target));
 }
        private unsafe UInt32 FastRead(void* src, UInt32 bytes)
        {
            UInt32 val = 0;
            if (BitConverter.IsLittleEndian)
                val = *((UInt32*)src);
            else
            {
                Byte* p = (Byte*)src;
                switch (bytes)
                {
                    case 4:
                        val = (UInt32)(*p) | (UInt32)(*(p + 1)) << 8 | (UInt32)(*(p + 2)) << 16 | (UInt32)(*(p + 3)) << 24;
                        break;
                    case 3:
                        val = (UInt32)(*p) | (UInt32)(*(p + 1)) << 8 | (UInt32)(*(p + 2)) << 16;
                        break;
                    case 2:
                        val = (UInt32)(*p) | (UInt32)(*(p + 1)) << 8;
                        break;
                    case 1:
                        val = (UInt32)(*p);
                        break;
                    default: break;
                }
            }

            return val;
        }
Example #20
0
 public static unsafe int AFCDirectoryRead(void* conn, void* dir, ref string buffer)
 {
     int ret;
     void* ptr = null;
     ret = AFCDirectoryRead(conn, dir, ref ptr);
     if ((ret == 0) && (ptr != null))
     {
         IntPtr ipPtr = new IntPtr(ptr);
         ArrayList bufferArray = new ArrayList();
         int curr = 0;
         while (true)
         {
             byte tmpByte = Marshal.ReadByte(ipPtr, curr);
             if (tmpByte != 0)
             {
                 bufferArray.Add(tmpByte);
                 curr++;
             }
             else
             {
                 break;
             }
         }
         buffer = System.Text.Encoding.UTF8.GetString((byte[])bufferArray.ToArray(typeof(byte)));
     }
     else
     {
         buffer = null;
     }
     return ret;
 }
 internal unsafe RuntimeMethodHandle GetCallableMethod(void* module) {
     return new RuntimeMethodHandle(ModuleHandle.GetDynamicMethod(
                                         module,
                                         m_methodBuilder.Name,
                                         (byte[])m_scope[m_methodSigToken], 
                                         new DynamicResolver(this)));
 }
Example #22
0
 public static unsafe int FontEngineAddTextureSync(int hasCode, bool useAlphaBlend, void* fontTexture)
 {
   lock (_lock)
   {
     return FontEngineAddTexture(hasCode, useAlphaBlend, fontTexture);
   }
 }
Example #23
0
 public static void* BoxDouble(void* methodTable, uint classSize, double value)
 {
     byte* memory = (byte*)AllocateObject(methodTable, classSize);
     double* destination = (double*)(memory + (nativeIntSize * 2));
     destination[0] = value;
     return memory;
 }
Example #24
0
		private static extern unsafe bool ReadFile(
			IntPtr hFile,                       // handle to file
			void* pBuffer,                      // data buffer
			int NumberOfBytesToRead,            // number of bytes to read
			int* pNumberOfBytesRead,            // number of bytes read
			int Overlapped                      // overlapped buffer
			);
Example #25
0
        /// <summary>
        /// This function requests allocation of an array.
        /// </summary>
        /// <param name="methodTable">Pointer to the array method table.</param>
        /// <param name="elementSize">The size of a single element in the method table.</param>
        /// <param name="elements">The number of elements to allocate of the type.</param>
        /// <returns>A ptr to the allocated memory.</returns>
        /// <remarks>
        /// The allocated object is not constructed, e.g. the caller must invoke
        /// the appropriate constructor in order to obtain a real object. The object header
        /// has been set.
        /// </remarks>
        public static unsafe void* AllocateArray(void* methodTable, uint elementSize, uint elements)
        {
            if (elements < 0)
            {
                throw new OverflowException();
            }

            // HACK: Add compiler architecture to the runtime
            uint nativeIntSize = 4;

            //
            // An array has the following memory layout:
            //   - IntPtr MTable
            //   - IntPtr SyncBlock
            //   - int length
            //   - ElementType[length] elements
            //
            uint allocationSize = (uint)(nativeIntSize + (elements * elementSize));

            void* memory = AllocateObject(methodTable, allocationSize);

            uint* destination = (uint*)memory;
            Memset((byte*)(destination + 3), 0, (int)allocationSize);
            destination[2] = elements;

            return memory;
        }
Example #26
0
 /// <summary>
 /// Frees a memory block.
 /// </summary>
 /// <param name="block"></param>
 public static void Free(void* block)
 {
     if (!HeapFree(_ph, 0, block))
     {
         throw new InvalidOperationException();
     }
 }
Example #27
0
        internal void AddScalar(void* value, int size)
        {
            var pb = (byte*)value;
            if (this.bufferNesting == 0)
            {
                var scratchOld = this.scratch;
                var scratchNew = scratchOld + size;
                if (this.scratchEnd < scratchNew)
                {
#if PROJECTN
                    throw new IndexOutOfRangeException(SR.GetResourceString("EventSource_AddScalarOutOfRange", null));
#else
                    throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_AddScalarOutOfRange"));
#endif
                }

                this.ScalarsBegin();
                this.scratch = scratchNew;

                for (int i = 0; i != size; i++)
                {
                    scratchOld[i] = pb[i];
                }
            }
            else
            {
                var oldPos = this.bufferPos;
                this.bufferPos = checked(this.bufferPos + size);
                this.EnsureBuffer();
                for (int i = 0; i != size; i++, oldPos++)
                {
                    this.buffer[oldPos] = pb[i];
                }
            }
        }
 private static RuntimeTypeHandle GetTypeHandle(void* obj)
 {
     // TypeDefinition is located at the beginning of object (i.e. *obj )
     RuntimeTypeHandle handle = new RuntimeTypeHandle();
     ((uint*)&handle)[0] = ((uint*)obj)[0];
     return handle;
 }
Example #29
0
		/// <summary>
		/// Reads structure from the input stream preserving its endianess.
		/// </summary>
		/// <param name="reader"></param>
		/// <param name="pStruct"></param>
		/// <param name="len"></param>
		unsafe internal static void ReadStruct(BinaryReader reader, void* pStruct, int len)
		{
			byte* p = (byte*) pStruct;

			if (System.BitConverter.IsLittleEndian) {
				// On a little-endian machine read data in 64-bit chunks,
				// this won't work on big-endian machine because
				// BinaryReader APIs are little-endian while
				// memory writes are platform-native.
				// This seems faster than ReadBytes/Copy method
				// in the "else" clause, especially if used often
				// (no extra memory allocation for byte[]?).
				int whole = len >> 3;
				int rem = len & 7;

				for (int i = whole; --i >= 0;) {
					long qw = reader.ReadInt64();
					Marshal.WriteInt64((IntPtr) p, qw);
					p += sizeof (long);
				}
				for (int i = rem; --i >= 0;) {
					*p++ = (byte) reader.ReadByte();
				}
			} else {
				byte [] buff = reader.ReadBytes(len);
				Marshal.Copy(buff, 0, (IntPtr) p, len);
			}
		}
    unsafe public static Object Box(void* ptr, Type type)
    {
      Contract.Ensures(Contract.Result<System.Object>() != null);
      Contract.Ensures(type.IsPointer == true);

      return default(Object);
    }