public static extern UInt32 STDFUFILES_SetImageElement(IntPtr handle, UInt32 dwRank, bool bInsert, [MarshalAs(UnmanagedType.Struct)] STDFUFILES_DfuImageElement Element);
public static bool CreateDfuFile(List <BinaryFileInfo> binFiles, string dfuName, UInt16 vid = defaultSTMVid, UInt16 pid = defafultSTMPid, UInt16 fwVersion = defaultFwVersion) { IntPtr dfuFileHandle = (IntPtr)0; IntPtr imageFileHandle = (IntPtr)0; // start creating a new DFU file for output var retCode = STDFUFILES_CreateNewDFUFile(dfuName, ref dfuFileHandle, vid, pid, fwVersion); if (retCode == STDFUFILES_NOERROR) { retCode = STDFUFILES_CreateImage(ref imageFileHandle, 0); retCode = STDFUFILES_SetImageName(imageFileHandle, "nanoFramework"); uint fileCounter = 0; // loop through collection of bin files and add them foreach (BinaryFileInfo file in binFiles) { byte[] fileData = File.ReadAllBytes(file.FileName); // get required memory size for byte array int size = Marshal.SizeOf(fileData[0]) * fileData.Length; STDFUFILES_DfuImageElement element = new STDFUFILES_DfuImageElement(); element.dwAddress = file.Address; element.dwDataLength = (uint)fileData.Length; // allocate memory from the unmanaged memory element.Data = Marshal.AllocHGlobal(size); // copy the byte array to the struct Marshal.Copy(fileData, 0, element.Data, fileData.Length); // get image from HEX file retCode = STDFUFILES_SetImageElement(imageFileHandle, fileCounter++, true, element); // free unmanaged memory Marshal.FreeHGlobal(element.Data); if (retCode != STDFUFILES_NOERROR) { // error adding this file Console.WriteLine(); Console.WriteLine($"ERROR: adding {file.FileName}"); Console.WriteLine(); return(false); } Console.WriteLine($"Adding file to image: {file.FileName}"); } // add image to DFU file retCode = STDFUFILES_AppendImageToDFUFile(dfuFileHandle, imageFileHandle); if (retCode != STDFUFILES_NOERROR) { // error adding this file Console.WriteLine(); Console.WriteLine($"ERROR: adding image to DFU file"); Console.WriteLine(); return(false); } // image file added, close DFU file STDFUFILES_CloseDFUFile(dfuFileHandle); Console.WriteLine(); Console.WriteLine($"DFU generated: {dfuName}"); Console.WriteLine($"Vendor ID: {vid.ToString("X4")}"); Console.WriteLine($"Product ID: {pid.ToString("X4")}"); Console.WriteLine($"Version: {fwVersion.ToString("X4")}"); Console.WriteLine(); // clean-up if (retCode == STDFUFILES_NOERROR) { // destroy image STDFUFILES_DestroyImage(ref imageFileHandle); } } return(true); }