none
question on marshalling from unmanaged to managed

    Question

  • i think im a little confused on the marshalling process. lets say i have an unmanaged C struct like so

    struct myStruct
    {
      int n1;
      int n2;
      char str1[10];
      char str2[2][5];
    }


    and i would like to pass this to a .net dll. the dll will mostly read from the struct (and maybe even change a value here or there ).  i would have a parallel managed struct on the dll side that mimics the unmanaged side.  most of the examples ive seen would have something similar to

    public struct myStruct
    {
      public int n1;
      public int n2;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
      public string str1;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
      public string str2_1;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
      public string str2_2;
    }

    but if i have a function that basically copies(and marshals) the data from the C struct to the managed .net struct do i need to define the struct with the MarshalAs attributes? couldnt i just have a managed struct like

    public struct myStruct
    {
      public int n1;
      public int n2;
      public string str1;
      public string str2_1;
      public string str2_2;
    }

    copy over the data to this one and work with it from there?

    Wednesday, January 03, 2007 2:51 PM

All replies

  • to make it even more clearer... lets say i have a function that does the following:

    public void MarshalData( ... )
    {
       .
       .
       .
       myManagedStruct.n1 = unmanagedStruct.n1;
       myManagedStruct.n2 = unmanagedStruct.n2;
       myManagesStruct.str1 = Marshal::PtrToStringAnsi( (IntPtr)unmanagedStruct.str1, 10 );
       myManagesStruct.str2_1 = Marshal::PtrToStringAnsi( (IntPtr)unmanagedStruct.str2[0], 5 );
       myManagesStruct.str2_2 = Marshal::PtrToStringAnsi( (IntPtr)unmanagedStruct.str2[1], 5 );
    }

    do i still need the MarshalAs attributes in the managed struct defintion?

    Wednesday, January 03, 2007 3:42 PM