平台调用错误:尝试读取或写入受保护的内存。

5

我在尝试使用平台调用示例改变字符串的大小写时遇到了错误。

以下是目前的代码:

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();   
    }
}

我不确定我的问题出在哪里,但我认为它与EntryPoint有关。

我必须使用Unicode,而CharLowerBuffW也无法解决问题。

我该如何修复这个问题?

2个回答

3

Microsoft的文档指出CharLowerBuffA是该方法的ANSI变体,但您正在指定Unicode。

尝试使用ANSI - 通过指定CharSet = CharSet.Ansi - 或者如果您需要Unicode,请使用CharLowerBuffWCharUpperBuffW

此外,该方法需要两个参数。您没有第二个参数。因此,请尝试以下操作:

[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);

并像这样调用:

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

如果这仍然无法解决问题,那么尝试使用字符数组,就像NatarajC提到的那样。

2
CharUpperBuffW得到了相同的结果,我确实需要Unicode。 - Craig Gallagher
我还注意到你缺少长度参数。我已经更新了我的答案。 - Gabriel Luci

1
同样的结果意味着它仍然出现相同的错误,请尝试在调用方法时使用string.ToCharArray(),并将签名更改为字符数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接