[英]C# How to write bytes into the middle of a byte[] array
下面的 function ReadPipe() 讀取字節塊,我需要將每個塊到 go 到 byte[] packet_buffer 中的下一個位置。 但我不知道如何告訴.ReadPipe 在 packet_buffer 中寫入字節。
如果是 C,我可以指定:*packet_buffer[下一個塊的字節索引]
如何在 C# 中執行此操作?
public static int receive_SetStreamPipe_2( byte[] packet_buffer, int bytes_to_read )
{
uint received_chunk_bytes = 0;
int remaining_bytes = bytes_to_read;
int total_transferred_bytes = 0;
// Use DataPipeInformation to get the actual PipeID
ftStatus = USB_device_selection0.SetStreamPipe( FT_pipe_information.PipeId, (UInt32)bytes_to_read );
if (ftStatus != FTDI.FT_STATUS.FT_OK)
return -(int)ftStatus; // lookup: FTDI.FT_STATUS
// For each chunk 'o bytes:
for(;;)
{
// Read chunk of bytes from FPGA:
ftStatus = USB_device_selection0.ReadPipe( FT_pipe_information.PipeId,
packet_buffer( remaining_bytes ) , <<<<<<<<<<<<<< THIS WON'T WORK
(uint)remaining_bytes,
ref received_chunk_bytes );
if (ftStatus != FTDI.FT_STATUS.FT_OK)
return -(int)ftStatus; // lookup: FTDI.FT_STATUS
total_transferred_bytes += (int)received_chunk_bytes;
remaining_bytes -= (int)received_chunk_bytes;
// Get more if not done:
if( total_transferred_bytes < bytes_to_read )
{
continue; // go get more
}
return 0;
}
}
根據 CodeCaster 的回復,到目前為止,最好的答案是我已要求制造 USB 主機驅動程序的 FTDI 公司提供帶有偏移的過載。
對您的代碼做出以下假設,我真的不應該這樣做,請閱讀 [詢問] 並提供所有相關細節:
receive_SetStreamPipe_2(byte[] packet_buffer, int bytes_to_read)
:
packet_buffer
中接收一個至少為bytes_to_read
長的數組,並且需要准確地填充bytes_to_read
字節USB_device_selection0.ReadPipe(FT_pipe_information.PipeId, packet_buffer, (uint)remaining_bytes, ref received_chunk_bytes)
:
packet_buffer
並且沒有偏移量的過載(例如Stream.Write(buffer, offset, count)
)remaining_bytes
字節,但可能更少received_chunk_bytes
分配給已讀取的字節數然后您需要引入一個臨時緩沖區,將其復制到最終緩沖區。 應該從 API 信息中獲得該緩沖區的最佳大小,但我們取 1024 個字節:
uint received_chunk_bytes = 0;
int remaining_bytes = bytes_to_read;
int total_transferred_bytes = 0;
// Create a smaller buffer to hold each chunk
int chunkSize = 1024;
byte[] chunkBuffer = new byte[chunkSize];
// ...
for (;;)
{
// Read chunk of bytes from FPGA into chunkBuffer, chunk size being the the buffer size or the remaining number of bytes, whichever is less
ftStatus = USB_device_selection0.ReadPipe(FT_pipe_information.PipeId,
chunkBuffer
(uint)Math.Min(chunkSize, remaining_bytes),
ref received_chunk_bytes);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
return -(int)ftStatus; // lookup: FTDI.FT_STATUS
// Copy the chunk into the output array
Array.Copy(chunkBuffer, 0, packet_buffer, total_transferred_bytes, received_chunk_bytes);
total_transferred_bytes += (int)received_chunk_bytes;
remaining_bytes -= (int)received_chunk_bytes;
// ...
如果是 C,我可以指定:*packet_buffer[下一個塊的字節索引]
你知道緩沖區溢出錯誤是什么嗎? 因為這就是我們得到緩沖區溢出錯誤的方式! 不要寫過去你為數組分配的 memory,否則天知道你在那里覆蓋了什么!
在 C# 中 - 與大多數其他語言一樣 - Arrays 固定為您在創建它們時提供的大小。 與許多其他語言不同,C#(實際上是 .NET)不允許您通過寫過去而意外導致緩沖區溢出。 對給定的每個索引都有一個健全性檢查,這樣就沒有人把事情搞砸了。
如果您想要一個 Automagicalyl 增長並允許隨機插入的數組, List<byte>
是您正在尋找的機器人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.