C#--尝试读取或写入受保护的内存,这通常指示其他内存已损坏。

记:

  近期在C#中调用别人的DLL的时候有时候出现了 尝试读取或写入受保护的内存 。这通常指示其他内存已损坏 的问题。

 

  错误类型:System.AccessViolationException。 

 

  问题位置:在与C++ dll规定传参的类型用的是string导致

 

  问题原因:C++ string类的字符在内存的储存位置:数据<=16字节,在当前栈区;数据>16字节,在堆区

       C# string是存放在堆区的。

 

  解决方案:在传值的时候用指针,再做转换就好了。

    public class APP_DLL
    {
        [DllImport("ruihua.dll", CallingConvention = CallingConvention.Cdecl)] //引入dll,并设置字符集
        public static extern int test(byte[] src1, int w1, int h1, int channel1, byte[] src2, int w2, int h2, int channel2, string str);
    }

  改为:

    public class APP_DLL
    {
        [DllImport("ruihua.dll", CallingConvention = CallingConvention.Cdecl)] //引入dll,并设置字符集
        public static extern int test(byte[] src1, int w1, int h1, int channel1, byte[] src2, int w2, int h2, int channel2, IntPtr str);
    }

  C# string转IntPtr方法:

  IntPtr ptrIn = Marshal.StringToHGlobalAnsi(obj.ToString());

  C# IntPtr转string方法:

  string retlust = Marshal.PtrToStringAnsi(ptrIn);  

 

posted @ 2020-04-14 11:05  让挑战成为习惯  阅读(9336)  评论(0编辑  收藏  举报