Search code examples
c#cdlldata-structurespinvoke

pinvoke: structure filled on the C side, but data gone when back home


I have a C DLL being called by a C# app, exchanging data using pinvoke. In the following, I have a simple class consisting of an int and 2 arrays of chars. Everything works dandy up to a point: the C# calls the DLL correctly (using "getStreamGroup"), and the DLL fills the passed streamGroup structure with the correct data.

But, once the C function is done, and we are back on the C# side, the streamGroup that got passed and filled with the correct data is now barren: 3 null values. No errors/warnings from VS2010. This is a 64bit app. Any ideas?

#define STREAM_COUNT 9000

typedef struct s_streamGroup
{
    int systemDefinedGroup;

    char name[BUFFER_SIZE_128];
    char streamList[STREAM_COUNT];

} streamGroup;


public class streamGroup
{
    public int systemDefinedGroup;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = constants.BUFFER_SIZE_128)]
    public byte[] name;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = constants.STREAM_COUNT)]
    public byte[] streamList;
}


DLL int getStreamGroup( int groupIndex, streamGroup *RequestedStreamGroup)
{   
    *RequestedStreamGroup = Environment.StreamGroup[groupIndex];
    return(DLL_NO_ERROR);
}

[DllImport(constants.DLL_PATH, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int getStreamGroup([In] int groupIndex, [In, Out] streamGroup group);

Solution

  • You need [StructLayout(LayoutKind.Sequential)] before streamGroup.

    If that's not enough please make your code a little more clear. I'm not sure what code is in what project (if I understand correct you have a native C++ project and a C# project). Please give two separate listings showing which is which, or explain what you're doing if my understanding is incorrect.