Search code examples
c#c++.netpinvoke

_BitScanForward in C#?


I am translating a program written in C++ to C#, and I have come across an intrinsic function that I cannot work around. In C++ this is known as:

unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask);

If I only knew what DLL, if any, the intrinsic functions were in, I could use P/Invoke. Since I do not know, I looked for alternatives in the .NET framework, but I have come up empty handed.

Does anyone know how use P/Invoke on _BitScanForward, or an .NET method that does the same thing?

Any help is appreciated, thank you.


Solution

  • Intrinsic functions aren't in any library, they're implemented inside the CPU, the compiler emits the machine code which the CPU recognizes as evoking this particular behavior.

    They're a way of getting access to instructions that don't have a simple C equivalent.

    Until the .NET optimizer becomes smart enough to recognize them (for example, the Mono JIT recognizes some SIMD instructions, encoded in MSIL as calls to functions of a particular class, similarly the .NET JIT replaces calls to System.Math methods with floating-point operations), your C# code is doomed to run an order of magnitude slower than the original C++.