• 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);  
  • 相关阅读:
    面试1
    初级算法-数组1
    程序员常用单词
    SpringBoot
    JDBC
    animate.css 实现 网页滚动指定位置添加动画
    解决打包上线缓存问题
    组件之间双向绑定
    按照给定数组排序原数组
    扩展运算符... 的使用
  • 原文地址:https://www.cnblogs.com/mexihq/p/12696579.html
Copyright © 2020-2023  润新知