日期:2014-05-18  浏览次数:21109 次

C#调用dll “尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
编译OK,调试时候显示的错误
尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

************** 异常文本 **************
System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
  在 HZbox.HZjudge.DoRecognize(Byte[] byteSerializedCh, Int32 iByteNum, Int16 chDestCh, Int16& chWrittenCh, Double[] pEvalout, Int32 iENum, Int32[] state, Byte[] ch)
  在 HZbox.HZjudge.Judge() 位置 I:\GoogleCode\hzapp\HZcomponent.HZbox\HZjudge.cs:行号 114


dll是C++的,是写.def的方式导出的方法
原来的声明是这样的
C/C++ code

BOOL DoRecognize(
                const unsigned char* pWriteData, 
                const int iDataLen, 
                const unsigned short iDestWChar,
                unsigned short* iWrittenChar, 
                double* pEvalOut, 
                const int iENumber,
                int *state,
                char *cs);


用在C#里我写成了
C# code

[DllImport(@"C:\Windows\System32\RIT.dll", EntryPoint="DoRecognize")]
static extern int DoRecognize(
                byte[] byteSerializedCh,
                int iByteNum,
                short chDestCh,
                ref short chWrittenCh,
                double[] pEvalout,
                int iENum,
                int[] state,
                byte[] ch);


总觉得是不是类型错了。

另外还有一点不知道值不值得一说,
这个dll回读取txt文件的,一开始调用是文件读不到,所以我把dll读取的文件路径都改成了绝对路径,放在system32下。
然后就变成了这样的错误,请高手指教~

------解决方案--------------------
数组越界了吧?检查一下各个数组的大小是否符合函数的要求。
------解决方案--------------------
二者都如下改:

C/C++ code

// 注意你的编译方式改为Unicode
extern "C" __declspec(dllexport)
BOOL __stdcall DoRecognize( const unsigned char* pWriteData, 
                const int iDataLen, const unsigned short iDestWChar,
                unsigned short* iWrittenChar, double* pEvalOut, 
                const int iENumber, int *state, char *cs);

------解决方案--------------------
类型问题
参考
------解决方案--------------------
也用指针,使用fix试试看
------解决方案--------------------
探讨
引用:
数组越界了吧?检查一下各个数组的大小是否符合函数的要求。

那是不是应该显示 System.OutofMemoryException