text stringlengths 0 13.4k |
|---|
} |
[DllImport("users.dll")] |
public static extern bool GetCurrentUser(out USER user); |
Section 27.2: Marshaling unions |
Value-type fields only |
C++ declaration |
typedef union |
{ |
char c; |
GoalKicker.com – .NET Framework Notes for Professionals |
95 |
int i; |
} CharOrInt; |
C# declaration |
[StructLayout(LayoutKind.Explicit)] |
public struct CharOrInt |
{ |
[FieldOffset(0)] |
public byte c; |
[FieldOffset(0)] |
public int i; |
} |
Mixing value-type and reference fields |
Overlapping a reference value with a value type one is not allowed so you cannot simply use the FieldOffset(0) |
text; FieldOffset(0) i; will not compile for |
typedef union |
{ |
char text[128]; |
int i; |
} TextOrInt; |
and generally you would have to employ custom marshaling. However, in particular cases like this simpler technics |
may be used: |
[StructLayout(LayoutKind.Sequential)] |
public struct TextOrInt |
{ |
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] |
public byte[] text; |
public int i { get { return BitConverter.ToInt32(text, 0); } } |
} |
Section 27.3: Calling a Win32 dll function |
using System.Runtime.InteropServices; |
class PInvokeExample |
{ |
[DllImport("user32.dll", CharSet = CharSet.Auto)] |
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, int options); |
public static void test() |
{ |
MessageBox(IntPtr.Zero, "Hello!", "Message", 0); |
} |
} |
Declare a function as static extern stting DllImportAttribute with its Value property set to .dll name. Don't |
forget to use System.Runtime.InteropServices namespace. Then call it as an regular static method. |
The Platform Invocation Services will take care of loading the .dll and finding the desired finction. The P/Invoke in |
most simple cases will also marshal parameters and return value to and from the .dll (i.e. convert from .NET |
datatypes to Win32 ones and vice versa). |
GoalKicker.com – .NET Framework Notes for Professionals |
96 |
Section 27.4: Using Windows API |
Use pinvoke.net. |
Before declaring an extern Windows API function in your code, consider looking for it on pinvoke.net. They most |
likely already have a suitable declaration with all supporting types and good examples. |
Section 27.5: Marshalling arrays |
Arrays of simple type |
[DllImport("Example.dll")] |
static extern void SetArray( |
[MarshalAs(UnmanagedType.LPArray, SizeConst = 128)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.