Unsafe DllImport
-
Hi. I'm using a function from a dll. It's imported with DllImport and marked as unsafe because the function returns a pointer to a memory array that the function allocates memory for (at least I think this is why).
[DllImport("netapi32.dll", ExactSpelling = true, SetLastError = true)] unsafe public static extern int NetWkstaTransportEnum( [MarshalAs(UnmanagedType.LPWStr)] string ServerName, uint level, **uint* pBufptr,** uint prefmaxlen, ref uint entriesread, ref uint totalentries, ref uint resumehandle );
How does it affect my program to compile with the /unsafe switch? Is it possible to define the above DllImport in a way that it will not be unsafe? BR Christian -
Hi. I'm using a function from a dll. It's imported with DllImport and marked as unsafe because the function returns a pointer to a memory array that the function allocates memory for (at least I think this is why).
[DllImport("netapi32.dll", ExactSpelling = true, SetLastError = true)] unsafe public static extern int NetWkstaTransportEnum( [MarshalAs(UnmanagedType.LPWStr)] string ServerName, uint level, **uint* pBufptr,** uint prefmaxlen, ref uint entriesread, ref uint totalentries, ref uint resumehandle );
How does it affect my program to compile with the /unsafe switch? Is it possible to define the above DllImport in a way that it will not be unsafe? BR Christian -
Try to replace it with IntPtr.
My english is not so good. Please, correct my errors. Best regards, Alexey.
The pointer is actually a pointer to an array of structs. How would I do the conversion from IntPtr to the struct array?
[System.Runtime.InteropServices.StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct WKSTA_TRANSPORT_INFO_0 { public int wkti0_quality_of_service; public int wkti0_number_of_vcs; public IntPtr wkti0_transport_name; public IntPtr wkti0_transport_address; public int wkti0_wan_ish; }
-
Try to replace it with IntPtr.
My english is not so good. Please, correct my errors. Best regards, Alexey.
Thanks for the hint with IntPtr. I managed to convert it. Not that I think that the new sollution is less unsafe, but... ;-)