views:

150

answers:

3

Hi,

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

A: 

It is simple. When you map your structure that want to marshal to the managed structure, you need map alls field that both structures have. The remaining fields in managed code that you do not map to any field will be ignored automatically.

Khoa Tran
Thanks, but this is just plain wrong... .NET has no knowledge of the native structure, so it has no way of automatically ignoring a field
Thomas Levesque
+4  A: 

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; 
}
Mattias S
"There's no way to make the CLR ignore a field" : yes, you're probably right... I'll wait a few days in case someone has another idea, but that's probably the best answer I'll get. Thanks !
Thomas Levesque
A: 

Two methods: 1) use a class instead of a struct: sctructures are always passed by pointer to windows api or other native functions.... replacing a call to doThis(ref myStruct) with a call to doThis([In, Out] myClass) should do the trick. Once done this, you can simply access your not-to-be-marshaled fields with methods 2) as i already stated, structs are (quite) always passed by reference: hence the callee knows nothing about structure dimensions: what about simply leaving your additional fields be the last ones? When calling a native function that needs your structure's pointer and the structure's size, simply lie about its size, giving the one it would have without your extra fields. Doesn't know if it's a legal way to marshal such a structure back when obtaining it FROM a native function. Side question: does Marshaler process class fields marked as private? (hope not...)

Giancarlo Todone