[英]I Only get a Stackoverflow exception when stepping through program
该程序在运行时运行良好,但是当我尝试逐步执行时,得到:
“未知模块中发生了'System.StackOverflowException类型的未处理的异常。”
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace PInvokeTest
{
class Program
{
static void Main(string[] args)
{
int session_handle = 0;
int flag = 0;
int didsetup = 0;
int defPort = 0;
int i = 0, j = -1;
short[] ROM;
ROM = new short[9];
short type_test = 0;
short port_num = 0, port_type = 1;
byte[] state_buf = new byte[5125];
StringBuilder ID_buf = new StringBuilder();
StringBuilder serial = new StringBuilder();
StringBuilder serialtmp = new StringBuilder();
//Finds default device type and port
defPort = TMReadDefaultPort(out port_num, out port_type);
// get the TMEX driver version
Get_Version(ID_buf); // STACKOVERFLOW EXCEPTION HERE
...
Console.ReadKey();
}
[DllImport("IBFS32.dll")]
public static extern int TMExtendedStartSession(
short PortNum,
short PortType,
IntPtr EnhancedOptions
);
[DllImport("IBFS32.dll")]
public static extern short TMReadDefaultPort(
out short port_num,
out short port_type
);
[DllImport("IBFS32.dll")]
public static extern short Get_Version(
[MarshalAs(UnmanagedType.LPStr)]StringBuilder ID_buf
);
[DllImport("IBFS32.dll")]
public static extern short TMGetTypeVersion(
short port_type,
[MarshalAs(UnmanagedType.LPStr)]StringBuilder ID_buf
);
[DllImport("IBFS32.dll")]
public static extern short TMSetup(
int session_handle
);
[DllImport("IBFS32.dll")]
public static extern short TMNext(
int session_handle,
byte[] state_buf
);
[DllImport("IBFS32.dll")]
public static extern short TMRom(
int session_handle,
byte[] state_buf,
short[] ROM
);
[DllImport("IBFS32.dll")]
public static extern short TMEndSession(
int session_handle
);
}
}
是什么导致它仅在运行时不步进就可以工作? 我有另一个程序使用的代码非常相似(dll函数位于不同的类中),但是无论如何运行,它都会出现stackoverflow异常。
编辑:
当我使用该dll的64位版本并在x64中构建程序时,它一直都可以正常工作...我不知道该信息对您是否有帮助。
我需要运行32位版本。
您必须为StringBuilder指定初始容量(通过构造函数),以确保其足够大以存储结果。 您正在调用默认构造函数。
您可以改为传递System.Text.StringBuilder对象; 封送程序会将指针传递给可以操纵的非托管函数。 唯一的警告是,必须为StringBuilder分配足够的空间用于返回值,否则文本将溢出,从而导致P / Invoke引发异常。
StringBuilder ID_buf = new StringBuilder(MaxVersionLength);
是什么导致它仅在运行时不步进就可以工作?
最有可能在Release中运行代码,但在Debug中过渡,在这些情况下,由于在Debug模式下需要更多信息,因此可用堆栈大小会减少,因此用于执行具体代码的堆栈上的可用内存会变小,从而产生堆栈溢出异常,由于堆栈已满。
顺便说一下,您有一个stackoverflow危险异常,因此最好对其进行修复,直到在Release和生产环境中遇到相同的问题为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.