Invoke platform error tried to read or write protected memory

I get an error when I try to use the platform call example where I try to change the lower and upper case of a string.

Here is what I got so far:

class Program { [DllImport("User32.dll", EntryPoint = "CharLowerBuffA", ExactSpelling = false, CharSet = CharSet.Unicode, SetLastError = true )] public static extern string CharLower(string lpsz); [DllImport("User32.dll", EntryPoint = "CharUpperBuffA", ExactSpelling = false, CharSet = CharSet.Unicode, SetLastError = true )] public static extern string CharUpper(string lpsz); static void Main(string[] args) { string l = "teSarf"; string ChangeToLower = CharLower(l.ToLower()); string ChangeToUpper = CharUpper(l.ToUpper()); Console.WriteLine("{0}", ChangeToLower); Console.ReadLine(); } } 

I am not sure where I am going wrong, but I think it is related to EntryPoint .

I need to use Unicode and CharLowerBuffW .

How can i fix this?

+5
source share
2 answers

Microsoft documentation indicates that CharLowerBuffA is an ANSI version of this method, but you specify Unicode.

Try either using ANSI - specifying CharSet = CharSet.Ansi - or if you need Unicode, use CharLowerBuffW and CharUpperBuffW .

In addition, the method accepts two parameters. You do not have a second. So try the following:

 [DllImport("User32.dll", EntryPoint = "CharLowerBuffW", ExactSpelling = false, CharSet = CharSet.Unicode, SetLastError = true )] public static extern string CharLower(string lpsz, int cchLength); [DllImport("User32.dll", EntryPoint = "CharUpperBuffW", ExactSpelling = false, CharSet = CharSet.Unicode, SetLastError = true )] public static extern string CharUpper(string lpsz, int cchLength); 

And name it as follows:

 string ChangeToLower = CharLower(l, l.Length); 

If this still doesn't work, try using character arrays like NatarajC.

+3
source

The same result means that it still gives the same error, try using string.ToCharArray () when calling the method, change the signature to a char array.

+1
source

Source: https://habr.com/ru/post/1246891/


All Articles