通过 PInvoke 将 byte[] 作为 IntPtr 传递给 memset
Passing byte[] as IntPtr by PInvoke to memset
我需要将一个字节数组传递给 memset,由于 P/Invoke 笨拙需要 IntPtr。手工测试,它有效,但我正在寻求理论确认。这个方法对吗?
[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);
}
}
您的代码没有问题,可以正常工作。
在我看来,避免 unsafe
并将 memset
的参数声明为 byte[]
是完全合理的,而且在我看来更加清晰。我会这样声明:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr memset(byte[] dest, int c, IntPtr count);
请注意,最后一个参数是指针大小的 size_t
。
我也确实想知道为什么您选择在非托管代码中执行此操作,但大概您有自己的理由。
我需要将一个字节数组传递给 memset,由于 P/Invoke 笨拙需要 IntPtr。手工测试,它有效,但我正在寻求理论确认。这个方法对吗?
[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);
}
}
您的代码没有问题,可以正常工作。
在我看来,避免 unsafe
并将 memset
的参数声明为 byte[]
是完全合理的,而且在我看来更加清晰。我会这样声明:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr memset(byte[] dest, int c, IntPtr count);
请注意,最后一个参数是指针大小的 size_t
。
我也确实想知道为什么您选择在非托管代码中执行此操作,但大概您有自己的理由。