I need to pass a byte array to memset, which due to P/Invoke clunkiness takes IntPtr. Tested by hand, it works, but I am seeking theoretical confirmation. Is this method correct?
[DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
public static extern IntPtr MemSet(IntPtr dest, int c, int count);
static unsafe void ZeroMemset (byte[] data)
{
fixed (byte* bytes = data) {
MemSet ((IntPtr)bytes, 0, data.Length);
}
}
Your code is fine and will work correctly.
It would be perfectly reasonable, and much clearer in my view, to avoid unsafe
and declare the parameter to memset
to be byte[]
. I'd declare it like this:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr memset(byte[] dest, int c, IntPtr count);
Note that the final parameter is size_t
which is pointer sized.
I also do wonder why you are opting to do this at all in unmanaged code, but presumably you have your reasons.