Guest User

Untitled

a guest
Jul 19th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. _declspec(dllexport) void TestArray(wchar_t** OutBuff,int Count,int MaxLength)
  2. {
  3. for(int i=0;i<Count;i++)
  4. {
  5. wchar_t buff[25];
  6. _itow(i,buff,10);
  7. wcsncpy(OutBuff[i],buff,MaxLength);
  8. }
  9. }
  10.  
  11. class Program
  12. {
  13. [DllImport("Native.dll", EntryPoint = "?TestArray@@YAXPAPA_WHH@Z", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
  14. private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)]
  15. IntPtr[] OutBuff, int Count, int MaxLength);
  16.  
  17. static void Main(string[] args)
  18. {
  19. int count = 10;
  20. int maxLen = 50;
  21. IntPtr[] buffer = new IntPtr[maxLen];
  22. for (int i = 0; i < count; i++)
  23. buffer[i] = Marshal.AllocHGlobal(maxLen);
  24.  
  25. TestArray(buffer, count, maxLen);
  26.  
  27. string[] output = new string[count];
  28. for (int i = 0; i < count; i++)
  29. {
  30. output[i] = Marshal.PtrToStringUni(buffer[i]);
  31. Marshal.FreeHGlobal(buffer[i]); // crash is here, when count is 1
  32. Console.WriteLine(output[i]);
  33. }
  34.  
  35. Console.ReadKey();
  36. }
  37. }
  38. }
  39.  
  40. IntPtr[] buffer = new IntPtr[count]; // NOTE: not maxLen
  41. for (int i = 0; i < count; i++)
  42. buffer[i] = Marshal.AllocHGlobal(maxLen * sizeof(Char));
Add Comment
Please, Sign In to add comment