Search code examples
.netstructurepinvokemarshalling

How can I ignore a field when marshalling a structure with P/Invoke


I want to marshal a structure for use with P/Invoke, but this struct contains a field that is only relevant to my managed code, so I don't want it to be marshaled since it doesn't belong in the native structure. Is it even possible ? I was looking for an attribute similar to NonSerialized for serialization, but it doesn't seem to exist...

struct MyStructure
{
    int foo;
    int bar;

    [NotMarshaled] // This attribute doesn't exist, but that's the kind of thing I'm looking for...
    int ignored;
}

Any suggestion would be appreciated


Solution

  • There's no way to make the CLR ignore a field. I would instead use two structures, and perhaps make one a member of the other.

    struct MyNativeStructure 
    { 
        public int foo; 
        public int bar; 
    } 
    
    struct MyStructure 
    { 
        public MyNativeStruct native; 
        public int ignored; 
    }