/// <summary> /// Creates a new pointer to an unmanaged block of memory /// from an structure of the specified type. /// </summary> /// <remarks> /// The returned pointer should be freed by calling <see cref="GLib.GFree"/>. /// </remarks> /// <typeparam name="T">The type of structure to be created.</typeparam> /// <param name="structure">A managed object that holds the data to be marshaled. /// This object must be a structure or an instance of a formatted class.</param> /// <returns>A pointer to an pre-allocated block of memory of the specified type.</returns> public static IntPtr ToIntPtr <T>(this object structure) where T : struct { // Initialize unmanged memory to hold the struct. var ptr = GLib.GMalloc((ulong)Marshal.SizeOf(typeof(T))); // Copy the struct to unmanaged memory. Marshal.StructureToPtr(structure, ptr, false); return(ptr); }
/// <summary> /// Marshals a managed byte array to a C string. /// </summary> /// <remarks> /// The returned pointer should be freed by calling <see cref="GLib.GFree"/>. /// The byte array should not include the null terminator. It will be /// added automatically. /// </remarks> /// <param name="bytes">The managed byte array.</param> /// <returns>A pointer to the unmanaged string.</returns> public static IntPtr ToPtr(this byte[] bytes) { if (bytes == null) { return(IntPtr.Zero); } var ptr = GLib.GMalloc((ulong)bytes.Length + 1); Marshal.Copy(bytes, 0, ptr, bytes.Length); Marshal.WriteByte(ptr, bytes.Length, 0); return(ptr); }