简体   繁体   中英

c# Convert struct to int

Consider the following struct:

[StructLayout(LayoutKind.Sequential)]
struct CONTEXT
{
public UINT ContextFlags;
unsafe fixed byte unused[160];
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
unsafe fixed byte unused2[24];
}

And the following code:

Context ctx = new Context{ ContextFlags = 0x10007 };

Now, I would like to convert this struct representative (ctx) into type int.

int x = (int)ctx;

The above method will not work, can someone think of the correct way for this conversion to take place?

Thank you,

Evan

I'm suspicious that you plan on calling a Windows API method that uses this structure . Perhaps even this method . In this case, the .NET marshaller will handle this for you.

[DllImport("kernel32.dll")]
public static extern bool GetThreadContext(IntPtr thread, ref CONTEXT context);

Notice that you pass the structure using the ref keyword. The marshaller will take care of creating an unmanaged pointer to the structure and passing it on to the called method. It will also handle bring the pointer back as a structure should the method modify the structure's data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM