我前段时间已经实现了这个API,一切都运行良好,直到几周前我注意到它,间歇性崩溃,与.NET相关的着名Marshaling"尝试读取或写入受保护记忆。这通常表明其他内存已损坏"。我注意到还有一些与我打开的应用程序数量相关的模式,所以我假设它与内存有关。但是检查可用内存时,它仍然指向一个健康的状态,当它崩溃时。请看下面的功能:
C++
__declspec(dllexport) char* xReadData(char *p_buffer, int offset, int size)
{
// do nothing
return p_buffer;
}
C#
[DllImport(PathToDll, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr xReadData([Out] IntPtr buffer, int offset, int size);
// SIZE = amount of bytes to read (2^13)
IntPtr pnt = Marshal.AllocHGlobal(SIZE);
...
try
{
xReadData(pnt, 0, SIZE); >> crashing on [Managed to Native Transition]
}
catch
{
}
...
Marshal.FreeHGlobal(pnt);
根据我的分析,它在本机功能完成和再次返回托管代码之间崩溃。
提前致谢。
答案 0 :(得分:0)
if ((offset>-1) && (offset + size<= MAX_BYTES))
{
memcpy(p_buffer, &(input_list[offset]), size);
}
当offset
等于MAX_BYTES
且大小等于零时,该条件肯定会抛出异常。
input_list[MAX_BYTES]
超出范围。
另外,我希望你释放缓冲区: - &#39;)