المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Passing a pointer to array of structs via P/Invoke



C# Programming
07-14-2009, 08:30 PM
I'm passing an array of structs to an unmanaged method and just want to make sure that what I'm doing is correct.

Let's assume I have a struct defined as

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct
{
public MyStruct(string Name, uint Index, MyEnum flag)
{
//some code
}

[MarshalAs(UnmanagedType.LPTStr)]
public string mName;
public uint sIndex;
[MarshalAs(UnmanagedType.U4)]
public MyEnum mflag;
}

where MyEnum is some enum deriving from uint.

The calling code creates an array of these structs like this:

MyStruct [] structs =
{
new MyStruct("BEN", 0, MyEnum.FIRST),
new MyStruct("VAL", 1, MyEnum.FOURTH),
new MyStruct("ROG", 2, MyEnum.SECOND)
};

I then pass this array to the managed function which looks like this:

public static extern int SetMyStructs([MarshalAs(UnmanagedType.LPArray)] MyStruct [] structs)

which is supposed to map to the unmanaged function of:

int SetMyStructs(MyStruct * structs)

SetMyStructs is returning values indicating that the function is not executing correctly. Is passing an array of structs containing strings and integers possible and if so am I using the correct marshalling attributes? I just want to eliminate this array of structs as a possible reason for the failing function.