0

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

8
  • 1
    Sorry, what do you mean by converting a structure to integer? This doesn't make sense (your structure is much larger than 4 bytes). Do you want a pointer, maybe? Commented Aug 3, 2011 at 19:30
  • 1
    How do you want to convert almost 200-byte structure into int?.. I'm missing something probably... Commented Aug 3, 2011 at 19:31
  • Hm, what are you trying to do here? int has 32 bits, and your struct has many many more. So, do you need pointer or what? Commented Aug 3, 2011 at 19:32
  • I'm sorry - I am extremely new with this kind of stuff (just learning about pointers). I belive you are correct though, a pointer is what I'm looking for. Commented Aug 3, 2011 at 19:32
  • 1
    OK, if you are new, please tell us what do you PLAN TO DO with the 'int' you want here? Commented Aug 3, 2011 at 19:34

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Yes, this is the exact API that I am using ... Although when dynamically calling this API are you suggesting that I can use the ref keyword?
@Evan - On a side note, there's a website that can show you some of the API signatures like the one above.
@Evan: Your function signature is probably wrong. Please show us your code.
@Evan: hard to comment on that error without more code to look at. I would guess either a typo where your DLLImport resides or at the call site. Also, remove unsafe fixed from your two array declarations within the structure.
@Slaks I made this post a while ago, I think it died out but it has my full code in it: stackoverflow.com/questions/6921983/c-convert-intptr-into-int
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.