views:

482

answers:

1

I'm trying to call NtGetContextThread from C# on AMD64. The problem is that the CONTEXT structure for AMD64 needs to be aligned on a 16-byte boundary, and when I call NtGetContextThread I always get STATUS_DATATYPE_MISALIGNMENT. I'm aware that C# can align individual members of a struct using the Pack attribute, but it doesn't seem to be able to align the entire structure. Is there any way I could do this?

EDIT: Just to make it clear, I don't want to align individual members. I want to align the entire structure.

+1  A: 

From your question, it's not clear whether you fully understand the Pack property of the StructLayout attribute. See this msdn article for more information.

If I understand you correctly, what you're looking for is the ability to explicitly align each member of a struct individually. If that's your goal, you can do so using the StructLayout and FieldOffset attributes as follows:

[StructLayout(LayoutKind.Explicit)]
public struct Message
{
    [FieldOffset(0)]
    public int a;
    [FieldOffset(4)]
    public short b;
    [FieldOffset(6)]
    public int c;
    [FieldOffset(22)] //Leave some empty space just for the heck of it.
    public DateTime dt;

}

Beware, though, that the the .NET CF Marshaler has some rules that you may not expect. For example, arrays must always be aligned at 4-byte boundaries. There are workarounds for this issue, but you should be aware that problems like this may crop up.

Odrade
No, that is *not* what I want to do. I want to align the *entire* CONTEXT structure on a 16-byte boundary, not the individual fields, like DECLSPEC_ALIGN. And I know what the Pack property does, thank you very much.Currently I'm using RtlAllocateHeap with 16-byte alignment as a workaround.
wj32
There's no need to take it personally. The way you describe 'Pack' made it unclear whether you understood it. Pack is not an attribute, and it can't use to individually align anything. Maybe you can see how I got the wrong idea about the question.
Odrade
And, of course, I don't know the answer to your question (now that I understand it properly).
Odrade
Sorry for taking it a bit too personally :D.
wj32