code_junkie

Marshal C++ struct array into C#

Nov 11th, 2011
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #define MAXCHARS 15
  2.  
  3. typedef struct
  4. {
  5. char data[MAXCHARS];
  6. int prob[MAXCHARS];
  7. } LPRData;
  8.  
  9. void GetData(LPRData *data);
  10.  
  11. LPRData *Results;
  12. Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData));
  13. GetData( Results );
  14.  
  15. public struct LPRData
  16. {
  17.  
  18. /// char[15]
  19. [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
  20. public string data;
  21.  
  22. /// int[15]
  23. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
  24. public int[] prob;
  25. }
  26.  
  27. GetData(LPRData[] data);
  28.  
  29. [StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]
  30. public struct LPRData
  31. {
  32. /// char[15]
  33. [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
  34. public string data;
  35.  
  36. /// int[15]
  37. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
  38. public int[] prob;
  39. }
  40.  
  41. static extern void GetData([Out] out IntPtr ptr);
  42.  
  43. LPRData[] GetData()
  44. {
  45. IntPtr value;
  46. LPRData[] array = new LPRData[3];
  47. GetData(out value);
  48. for (int i = 0; i < array.Length; i++)
  49. {
  50. array[i] = Marshal.PtrToStructure(value, typeof(LPRData));
  51. value += value.ToInt32() + Marshal.SizeOf(typeof(LPRData));
  52. }
  53. return array;
  54. }
Add Comment
Please, Sign In to add comment