Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform Invoke error attempted to read or write protected memory

Tags:

I am getting am error when I am trying to use platform invoke example where I am trying to change the Lower and Upper case of 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 with this but I think it is to do with the EntryPoint.

I have to use Unicode and CharLowerBuffW didn't work either.

How can I fix this?

like image 729
Craig Gallagher Avatar asked Apr 11 '16 18:04

Craig Gallagher


1 Answers

Microsoft's documentation indicates that CharLowerBuffA is the ANSI variant of that method, but you are specifying Unicode.

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

As well, the method takes two parameters. You don't have the second one. So try this:

[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 call it like this:

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

If that still doesn't work, then try using character arrays, like NatarajC mentioned.

like image 184
Gabriel Luci Avatar answered Sep 28 '22 04:09

Gabriel Luci