unsafe public static Object Box(void* ptr, Type type)
    {
      Contract.Ensures(Contract.Result<System.Object>() != null);
      Contract.Ensures(type.IsPointer == true);

      return default(Object);
    }
Exemple #2
0
    public static async Task Main(string[] args)
#endif
    {
        unsafe {
            // Register a managed callback (will be called by UIButton, see main.m)
            delegate * unmanaged <void> unmanagedPtr = &OnButtonClick;
            ios_register_button_click(unmanagedPtr);
        }
        const string msg = "Hello World!\n.NET 5.0";

        for (int i = 0; i < msg.Length; i++)
        {
            // a kind of an animation
            ios_set_text(msg.Substring(0, i + 1));
            await Task.Delay(100);
        }

        Console.WriteLine("Done!");
#if CI_TEST
        await Task.Delay(5000);

        return(42);
#else
        await Task.Delay(-1);
#endif
    }
Exemple #3
0
 public static unsafe int FontEngineAddTextureSync(int hasCode, bool useAlphaBlend, void* fontTexture)
 {
   lock (_lock)
   {
     return FontEngineAddTexture(hasCode, useAlphaBlend, fontTexture);
   }
 }
Exemple #4
0
        public static void DoUnsafeThings()
        {
            delegate * < ref char, char, Action <char>, void > funcpointer = &Cserelj;

            char  a = 'm';
            char *b = &a;

Here:
            if (*b is 'f')
            {
                System.Console.WriteLine(*b);
            }
            else
            {
                funcpointer(ref a, 'f', a => System.Console.WriteLine($"Az a: {a}"));
                goto Here;
            }

            char another = a;

            System.Console.WriteLine(another);


            delegate * < ref int, int, Action <int>, void > funcintpointer = &Cserelj;
            int azta = 10;
Exemple #5
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);
 }
Exemple #6
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;
        }
 private unsafe int DirectInputEnumCreatedEffectsImpl(void* deviceInstance, IntPtr data)
 {
     var newEffect = new Effect((IntPtr)deviceInstance);
     Effects.Add(newEffect);
     // Return true to continue iterating
     return 1;
 }
Exemple #8
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;
        }
Exemple #9
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;
				}
			}
		}
Exemple #10
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];
                }
            }
        }
Exemple #11
0
 public void shift(void s, void b, void m) {
     object l = s.Length;
     if ((m == "l")) {
         for (j = 0; (j 
                     <= (b - 1)); j++) {
             object t = s.Substring(0, 1);
             for (i = 1; (i 
                         <= (l - 1)); i++) {
                 s.Substring((i - 1), 1) = s.Substring(i, 1);
             }
             
             s.Substring((l - 1), 1) = t;
         }
         
     }
     else if ((m == "r")) {
         for (int j = 0; (j 
                     <= (b - 1)); j++) {
             object t = s.Substring((l - 1), 1);
             for (i = l; (i <= 2); i = (i + -1)) {
                 s.Substring((i - 1), 1) = s.Substring(i, 1);
             }
             
             s.Substring(0, 1) = t;
         }
         
     }
     
     return s;
 }
        /// <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;
        }
 /// <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;
 }
Exemple #14
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
        }
Exemple #15
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);
			}
		}
Exemple #16
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);
            }
        }
Exemple #17
0
        public void Method()
        {
            delegate * < void > ptr1 = &FunctionPointers.Log;

            // This should work but it does not
            // void* v = &FunctionPointers.Log;
        }
        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;
        }
 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;
 }
Exemple #20
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();
     }
 }
 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;
 }
Exemple #22
0
        private unsafe static void MyHandleCleanFunc(void* a)
        {
            GCHandle gch = GCHandle.FromIntPtr((IntPtr)a);
            BinaryReader br = (BinaryReader)gch.Target;

            br.Close();
        }
Exemple #23
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
			);
Exemple #24
0
        static unsafe void InitializeCoreCLRBridge(InitializationOptions *options)
        {
            if (options->xamarin_objc_msgsend != IntPtr.Zero)
            {
                ObjectiveCMarshal.SetMessageSendCallback(ObjectiveCMarshal.MessageSendFunction.MsgSend, options->xamarin_objc_msgsend);
            }

            if (options->xamarin_objc_msgsend_super != IntPtr.Zero)
            {
                ObjectiveCMarshal.SetMessageSendCallback(ObjectiveCMarshal.MessageSendFunction.MsgSendSuper, options->xamarin_objc_msgsend_super);
            }

            if (options->xamarin_objc_msgsend_stret != IntPtr.Zero)
            {
                ObjectiveCMarshal.SetMessageSendCallback(ObjectiveCMarshal.MessageSendFunction.MsgSendStret, options->xamarin_objc_msgsend_stret);
            }

            if (options->xamarin_objc_msgsend_super_stret != IntPtr.Zero)
            {
                ObjectiveCMarshal.SetMessageSendCallback(ObjectiveCMarshal.MessageSendFunction.MsgSendSuperStret, options->xamarin_objc_msgsend_super_stret);
            }

            delegate * unmanaged <void> beginEndCallback            = (delegate * unmanaged <void>)options->reference_tracking_begin_end_callback;
            delegate * unmanaged <IntPtr, int> isReferencedCallback = (delegate * unmanaged <IntPtr, int>)options->reference_tracking_is_referenced_callback;
            delegate * unmanaged <IntPtr, void> trackedObjectEnteredFinalization = (delegate * unmanaged <IntPtr, void>)options->reference_tracking_tracked_object_entered_finalization;
            ObjectiveCMarshal.Initialize(beginEndCallback, isReferencedCallback, trackedObjectEnteredFinalization, UnhandledExceptionPropagationHandler);
        }
Exemple #25
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;
 }
 public static void BlockCopy(void* from, void* to, uint byteCount)
 {
     if (byteCount != 0)
     {
         BlockCopyCore((byte*)from, (byte*)to, byteCount);
     }
 }
 /// <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));
 }
 internal unsafe RuntimeMethodHandle GetCallableMethod(void* module) {
     return new RuntimeMethodHandle(ModuleHandle.GetDynamicMethod(
                                         module,
                                         m_methodBuilder.Name,
                                         (byte[])m_scope[m_methodSigToken], 
                                         new DynamicResolver(this)));
 }
Exemple #29
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;
		}
        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;
        }
Exemple #31
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;
 }
Exemple #32
0
		unsafe public ArgIterator (RuntimeArgumentHandle arglist, void *ptr)
		{
			sig = IntPtr.Zero;
			args = IntPtr.Zero;
			next_arg = num_args = 0;
			Setup (arglist.args, (IntPtr) ptr);
		}
 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;
 }
Exemple #34
0
 void Use()
 {
     delegate * < void > p1      = &Log;
     delegate * < int, void > p2 = &Log;
     delegate * managed <void> p3 = p1;
     Console.WriteLine(p1 == p3); // True
 }
Exemple #35
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;
 }
        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);
            }
        }
            public static void Use()
            {
                delegate * < void > a1      = &Log; // Log()
                delegate * < int, void > a2 = &Log; // Log(int i)

                a1();
                a2(4);
            }
Exemple #38
0
        public unsafe void Test()
        {
            Action <string> action1 = Console.WriteLine;

            action1("123");

            delegate * < string, void > action2 = &Console.WriteLine;
            action2("hello pointer");
        }
Exemple #39
0
    public static int Main(string[] args)
    {
        unsafe {
            delegate * unmanaged <void> unmanagedPtr = &Callback;
            invoke_external_native_api(unmanagedPtr);
        }

        return(counter);
    }
Exemple #40
0
            protected override IDisposable[] RequestHooks()
            {
                delegate * unmanaged <void *, void *, int, void> pSignalMeleeDamageHook = &OnSignalMeleeDamage;
                signalMeleeDamageHook = HookService.RequestHook <SignalMeleeDamageHook>(pSignalMeleeDamageHook, FunctionsLinux._ZN12CNWSCreature17SignalMeleeDamageEP10CNWSObjecti, HookOrder.Late);

                delegate * unmanaged <void *, void *, int, void> pSignalRangedDamageHook = &OnSignalRangedDamage;
                signalRangedDamageHook = HookService.RequestHook <SignalRangedDamageHook>(pSignalRangedDamageHook, FunctionsLinux._ZN12CNWSCreature18SignalRangedDamageEP10CNWSObjecti, HookOrder.Late);

                return(new IDisposable[] { signalMeleeDamageHook, signalRangedDamageHook });
            }
Exemple #41
0
    private static delegate *unmanaged[Stdcall] < void > LoadCallbackThrow(IntPtr context, LoadFunction load, string name)
    {
        delegate * unmanaged[Stdcall] < void > functionPtr = load(context, name);
        if (functionPtr == null)
        {
            throw new InvalidOperationException($"No function was found with the name {name}.");
        }

        return(functionPtr);
    }
Exemple #42
0
        private static unsafe void IjwTest(string libraryPath, string entryPointName)
        {
            Console.WriteLine($"Invoking {entryPointName} in '{libraryPath}'");

            IntPtr library = NativeLibrary.Load(libraryPath);
            IntPtr export  = NativeLibrary.GetExport(library, entryPointName);

            // Test is assuming __cdecl, no argument,s and void return for simplicity
            delegate * unmanaged[Cdecl] < void > entryPoint = (delegate * unmanaged[Cdecl] < void >)export;
            entryPoint();
        }
Exemple #43
0
    public static async Task <int> Main(string[] args)
    {
        mono_ios_set_summary($"Starting functional test");
        unsafe {
            delegate * unmanaged <void> unmanagedPtr = &Callback;
            invoke_external_native_api(unmanagedPtr);
        }
        Console.WriteLine("Done!");
        await Task.Delay(5000);

        return(counter);
    }
Exemple #44
0
        private static void SetupGameUpdateCallback()
        {
            if (!Util.IsInGame)
            {
                return;
            }

            Console.WriteLine($"GameUpdateFuncPtr = {((nint)GameUpdateFuncPtr).ToString("X16")}  (+{((nint)GameUpdateFuncPtr - Util.BaseAddress).ToString("X8")})");
            PrevGameUpdateFunc = (delegate * unmanaged <void>) * (void **)GameUpdateFuncPtr;
            delegate * unmanaged <void> newGameUpdateFunc = &GameUpdate;
            *(void **)GameUpdateFuncPtr = newGameUpdateFunc;
        }
Exemple #45
0
        public static void Use()
        {
            delegate * < void > a1         = &Log; // Log()
            delegate * < int, void > a2    = &Log; // Log(int i)
            delegate * < string, void > a3 = &Log; //Log(string p1)

            a1();
            a2(1);
            a3("a");

            // Error: ambiguous conversion from method group Log to "void*"
            // void* is a pointer to UNKNOWN type
            //void* v = &Log;
        }
        public unsafe InferenceEngineRequest(InferenceEngineExecutableNetwork executableNetwork)
        {
            _executableNetwork = executableNetwork;
            ie_exec_network_create_infer_request(executableNetwork.ExecutableNetwork, out _inferRequest).Check(nameof(ie_exec_network_create_infer_request));

#if NET5_0
            _handle = GCHandle.Alloc(this);
            var cbArray = Marshal.AllocHGlobal(sizeof(IntPtr) * 2);
            var span    = new Span <IntPtr>((void *)cbArray, 2);
            delegate * unmanaged[Cdecl] < IntPtr, void > unmanagedPtr = &CompleteCallBack;

            span[0]  = (IntPtr)unmanagedPtr;
            span[1]  = GCHandle.ToIntPtr(_handle);
            _cbArray = cbArray;
#endif
        }
Exemple #47
0
            protected override IDisposable[] RequestHooks()
            {
                delegate * unmanaged <void *, void *, uint, void> pCreatureExamineHook = &OnCreatureExamine;
                creatureExamineHook = HookService.RequestHook <CreatureExamineHook>(pCreatureExamineHook, FunctionsLinux._ZN11CNWSMessage41SendServerToPlayerExamineGui_CreatureDataEP10CNWSPlayerj, HookOrder.Earliest);

                delegate * unmanaged <void *, void *, uint, void> pDoorExamineHook = &OnDoorExamine;
                doorExamineHook = HookService.RequestHook <DoorExamineHook>(pDoorExamineHook, FunctionsLinux._ZN11CNWSMessage37SendServerToPlayerExamineGui_DoorDataEP10CNWSPlayerj, HookOrder.Earliest);

                delegate * unmanaged <void *, void *, uint, void> pItemExamineHook = &OnItemExamine;
                itemExamineHook = HookService.RequestHook <ItemExamineHook>(pItemExamineHook, FunctionsLinux._ZN11CNWSMessage37SendServerToPlayerExamineGui_ItemDataEP10CNWSPlayerj, HookOrder.Earliest);

                delegate * unmanaged <void *, void *, uint, void> pPlaceableExamineHook = &OnPlaceableExamine;
                placeableExamineHook = HookService.RequestHook <PlaceableExamineHook>(pPlaceableExamineHook, FunctionsLinux._ZN11CNWSMessage42SendServerToPlayerExamineGui_PlaceableDataEP10CNWSPlayerj, HookOrder.Earliest);

                return(new IDisposable[] { creatureExamineHook, doorExamineHook, itemExamineHook, placeableExamineHook });
            }
        /*-------------------------------------------------------
        *  C++ new and new_aligned
        *  The standard requires calling into `get_new_handler` and
        *  throwing the bad_alloc exception on failure. If we compile
        *  with a C++ compiler we can implement this precisely. If we
        *  use a C compiler we cannot throw a `bad_alloc` exception
        *  but we call `exit` instead (i.e. not returning).
        *  -------------------------------------------------------*/

        private static bool mi_try_new_handler(bool nothrow)
        {
            delegate * unmanaged[Cdecl] < void > h = std_get_new_handler();

            if (h == null)
            {
                if (!nothrow)
                {
                    // cannot throw in plain C, use exit as we are out of memory anyway.
                    exit(ENOMEM);
                }
                return(false);
            }
            else
            {
                h();
                return(true);
            }
        }
        private static T *TRY_D3D12MA_NEW <T>(D3D12MA_ALLOCATION_CALLBACKS *allocs)
            where T : unmanaged
        {
            T *p = null;

            while (p == null)
            {
                delegate * unmanaged[Cdecl] < void > h = win32_std_get_new_handler();

                if (h == null)
                {
                    Environment.Exit(ENOMEM);
                }

                h();
                p = Allocate <T>(allocs);
            }

            *p = default;
            return(p);
        }
        private static T *TRY_D3D12MA_NEW_ARRAY <T>(D3D12MA_ALLOCATION_CALLBACKS *allocs, nuint count)
            where T : unmanaged
        {
            T *p = null;

            while (p == null)
            {
                delegate * unmanaged[Cdecl] < void > h = win32_std_get_new_handler();

                if (h == null)
                {
                    Environment.Exit(ENOMEM);
                }

                h();
                p = AllocateArray <T>(allocs, count);
            }

            Unsafe.InitBlock(p, 0, (uint)(sizeof(T) * (int)count));
            return(p);
        }
Exemple #51
0
    public static async Task Main(string[] args)
    {
        unsafe {
            // Register a managed callback (will be called by UIButton, see main.m)
            delegate * unmanaged <void> unmanagedPtr = &OnButtonClick;
            ios_register_button_click(unmanagedPtr);
            delegate * unmanaged <void> unmanagedPtr2 = &OnApplyUpdateClick;
            ios_register_applyupdate_click(unmanagedPtr2);
        }
        deltaHelper = MonoDelta.DeltaHelper.Make();
        const string msg = "Hello World!\n.NET 5.0";

        for (int i = 0; i < msg.Length; i++)
        {
            // a kind of an animation
            ios_set_text(msg.Substring(0, i + 1));
            await Task.Delay(100);
        }

        Console.WriteLine("Done!");
        await Task.Delay(-1);
    }
Exemple #52
0
    private static unsafe void ManagedFunctionPointer()
    {
        {
            EqualsDelegate equalsFunc = Program.Equals;
            equalsFunc(1, 2);
        }

        {
            Func <int, int, bool> equalsFunc = Program.Equals;
            equalsFunc(1, 2);
        }

        {
            delegate * < int, int, bool > equalsFunc = &Program.Equals;
            equalsFunc(1, 2);

            delegate * managed <string, void> writeLineFunc = null;

            writeLineFunc = &Program.WriteLine;
            writeLineFunc("1 == 2: " + equalsFunc(1, 2));
        }

        {
            IntPtr pFunc = new IntPtr(1000);
            delegate * < void > unsafeFunc = (delegate * < void >)pFunc;
            // Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
            // unsafeFunc();
        }

        {
            delegate * < string, void > writeLineFunc = &Program.WriteLine;
            IntPtr ptr = new IntPtr(writeLineFunc);
            delegate * < void > unsafeFunc = (delegate * < void >)ptr;
            // Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
            // unsafeFunc();
        }
    }
Exemple #53
0
    private static void UnmanagedFunctionPointer()
    {
        IntPtr ptrKernel  = LoadLibrary("kernel32.dll");
        IntPtr ptrSleepEx = GetProcAddress(ptrKernel, "SleepEx");

        {
            SleepExDelegate sleepExFunc = Marshal.GetDelegateForFunctionPointer(ptrSleepEx, typeof(SleepExDelegate)) as SleepExDelegate;

            Console.WriteLine(DateTime.Now);
            sleepExFunc(2000, false);
            Console.WriteLine(DateTime.Now);
        }

        unsafe
        {
            delegate * unmanaged[Stdcall] < int, bool, int > sleepExFunc = (delegate * unmanaged[Stdcall] < int, bool, int >)ptrSleepEx;
            Console.WriteLine(DateTime.Now);
            sleepExFunc(2000, false);
            Console.WriteLine(DateTime.Now);
        }

        unsafe
        {
            // System.Runtime.CompilerServices.CallConvStdcall
            delegate * unmanaged[Stdcall] < void > ptr1 = null;

            // System.Runtime.CompilerServices.CallConvCdecl
            delegate * unmanaged[Cdecl] < void > ptr2 = null;

            // System.Runtime.CompilerServices.CallConvFastcall
            delegate * unmanaged[Fastcall] < void > ptr3 = null;

            // System.Runtime.CompilerServices.CallConvThiscall
            delegate * unmanaged[Thiscall] < void > ptr4 = null;
        }
    }
 protected override IDisposable[] RequestHooks()
 {
     delegate * unmanaged <void *, byte, void> pHook = &OnSetDetectMode;
     Hook = HookService.RequestHook <SetDetectModeHook>(pHook, FunctionsLinux._ZN12CNWSCreature13SetDetectModeEh, HookOrder.Early);
     return(new IDisposable[] { Hook });
 }
 void IVehicle.Gas
 void IVehicle.Brake
Exemple #56
0
 public void HandleUI(void effectInfo)
 {
 }
Exemple #57
0
	//loader
	void load_last
	
	
	//функция бесконечной отрисовки игровых уровней
	void on_next_click(int last_lvl)
Exemple #58
0
        void processTheImage

        void saveSeries(Color[,] a, Color[,] b, string name)
Exemple #59
0
 protected override IDisposable[] RequestHooks()
 {
     delegate * unmanaged <void *, ushort, void *, void *, void> pHook = &OnSendFeedbackMessage;
     Hook = HookService.RequestHook <SendFeedbackMessageHook>(pHook, FunctionsLinux._ZN12CNWSCreature19SendFeedbackMessageEtP16CNWCCMessageDataP10CNWSPlayer, HookOrder.Earliest);
     return(new IDisposable[] { Hook });
 }
Exemple #60
0
 protected override IDisposable[] RequestHooks()
 {
     delegate * unmanaged <void *, uint, uint, void> pHook = &OnPayToIdentifyItem;
     Hook = HookService.RequestHook <PayToIdentifyItemHook>(pHook, FunctionsLinux._ZN12CNWSCreature17PayToIdentifyItemEjj, HookOrder.Early);
     return(new IDisposable[] { Hook });
 }