Equivalent of C++'s sizeof(uint64Array) in C#?

Viewed 142

On this code : http://prng.di.unimi.it/xoshiro256plus.c They do this :

static const uint64_t JUMP[] = { 0x180ec6d33cfd0aba, 0xd5a61266f0c9392c, 0xa9582618e03fc9aa, 0x39abdc4529b1661c };

 for(int i = 0; i < sizeof JUMP / sizeof *JUMP; i++)

What does sizeof JUMP / sizeof *JUMP means and how to port it to c# ?

sizeof JUMP seems to be Marshal.Sizeof(JUMP) according to https://docs.microsoft.com/fr-fr/dotnet/api/system.runtime.interopservices.marshal.sizeof?view=netframework-4.8

But Marshal.Sizeof(*JUMP) cant be donne in safe mode and I cant use unsafe code.

And according to this page : https://en.cppreference.com/w/cpp/language/sizeof sizeof JUMP / sizeof *JUMP return array's length. So why not just put 4 instead as JUMP length is known ?

Thank.

2 Answers

why not just put 4 instead as JUMP length is known

because unlike C#'s arrays, you cannot simply access a Length property of an array in C++. Yes, 4 is the correct answer today but what if someone edits the array later and there are 3 or 5 entries? They have to remember to edit the for as well.

What does sizeof JUMP / sizeof *JUMP means and how to port it to c# ?

sizeof JUMP / sizeof *JUMP is the size in bytes of the total array divided by the size of the first array element. That gives you the length of the array.

It's the same as writing sizeof JUMP / sizeof JUMP[0]

In C# you just write "JUMP.Length"

for (int i = 0; i < JUMP.Length; i++)
{
}

On a sidenote, you do have limited sizeof capability in C#:

using System.Runtime.InteropServices;

    long[] arr = new long[10];

    Console.WriteLine("" + Marshal.SizeOf(arr[0]));

So you can translate *JUMP to JUMP[0]

Related