C function in the library

TCHAR* __stdcall W1251ToUtf8(CHAR* str)//функция пребразования строки из Windows-1251 в Unicode { int wsize = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); TCHAR* result = new TCHAR[wsize*sizeof(TCHAR)]; MultiByteToWideChar(CP_UTF8, 0, str, -1, result, wsize); return result; } 

Her ad in C # code

 [DllImport("D://EncodingStringData.dll", EntryPoint = "W1251ToUtf8")] static extern string W1251ToUtf8(string str); 

Place her call in the code

 string TextForEncoding = ReadFromFile(); string OutText = W1251ToUtf8(TextForEncoding); 

The first time the application just crashed, then added try catch

 try { string TextForEncoding = ReadFromFile(); string OutText = W1251ToUtf8(TextForEncoding); } catch (Win32Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } 

It crashed with an accessviolationexception error, now crashes without any error. Tell me what's wrong? There were suggestions that the matter is in accordance with TCHAR * and string, but it seems to be so correct.

has exited with code -1073740940 (0xc0000374). Here is the application termination code

  • one
    The approach is fundamentally wrong. Strings in .NET can only contain Unicode. Read from the file immediately in the desired encoding, the benefit is easy. - Alexander Petrov
  • Once again: the String class in .NET can only contain UTF16. To store strings in other encodings, use an array of bytes - byte[] . To convert from one encoding to another, use the System.Text.Encoding class. - Alexander Petrov

1 answer 1

This problem was solved in the following way. C # ad

 private static extern IntPtr W1251ToUtf8(string str); 

Using

 IntPtr OutText = W1251ToUtf8(TextForEncoding); result = Marshal.PtrToStringUni(OutText);