Reputation: 133
i'm trying to convert code from c++ to c#.. but i'm stuck. Can somebody let me know where i'm wrong?
C++ code is:
void CALLBACK Test(void *buffer, DWORD length)
{
BYTE *b=(BYTE*)buffer, temp[20000];
DWORD p=0;
while (p<length)
{
DWORD c=min(length-p, sizeof(temp));
memcpy(temp, b+p, c);
c=SendData(dummy, temp, c);
if (c==-1) break;
p+=c;
}
}
where is SendData(int, byte[], int)
And current c# code
void Test(IntPtr buffer, int length)
{
byte[] temp = new byte[20000];
byte[] b = new byte[length];
Marshal.Copy(buffer, b, 0, length);
long p=0;
while (p<length)
{
long c=Math.Min(length-p, 20000);
Array.Copy(temp, b+p, c);
c=SendData(dummy, temp, (int)c);
if (c==-1) break;
p+=c;
}
}
I'm not sure did I did it correctly, but I can see I cannot apply operator +
to b+s
because it's long
and byte[]
.
Thanks
Upvotes: 0
Views: 219
Reputation: 26633
In C++ you may add a DWORD (an int, really) to a pointer and the compiler knows to offset the address of the pointer by the specified amount. C# doesn't let you do that, normally. (There is a way to do pointer arithmetic in C#, but don't.) So, in the C# version, you need another way to copy at offset p
relative to the start of b
. One of the overloads of Array.Copy will let you do that. Something like:
Array.Copy(temp, 0, b, p, c);
Upvotes: 2
Reputation: 5470
I think you want to use the 5-arg version of Array.Copy, which lets you pass offsets into both the start and destination arrays. This is the more "C#" way of doing things as opposed to pointer arithmetic.
Upvotes: 2
Reputation: 1509
You may want to look at: How to split a byte array, because that is in effect what you are trying to accomplish with the b+p
portion.
Upvotes: 0