问题
In the middle of translating some code from C++ to C#, I found this,
unsigned char *p = m_pRecvBuffer + 5;
unsigned int noncelen1 = *p * 256 + p[1];
How do I translate this into C#? m_pRecvBuffer
is a char-array, however I store it as a byte-array.
回答1:
Something akin to
byte[] p = new byte[m_pRecvBuffer.Length - 5];
Array.Copy(m_precvBuffer, p, m_pRecvBuffer.Length - 5);
uint noncelen1 = p[0] * 256 + p[1];
But in that case I don't think you actually need to use an array copy. Just using
uint noncelen1 = p[5] * 256 + p[6];
should be enough, I guess.
回答2:
Hmm I wonder if some refactoring would be in order for this piece of code. Yes you can use pointers in C#. However, based on that snippet there may be better options. It looks like you're trying to read parts of an incoming stream. Maybe C#'s stream library would work better for this piece of your code?
回答3:
You analyse what the code actually does and translate behaviour, not code. While you could use unsafe
methods and pointer arithmetic in c#, this will probably create more problems than it will solve.
回答4:
Assuming RecvBuffer is declared as byte[], you would do something like this:
int noncelen1 = RecvBuffer[5] * 256 + RecvBuffer[6];
来源:https://stackoverflow.com/questions/4837561/unsigned-char-pointer-in-c