问题与longjmp [英] question with longjmp

查看:208
本文介绍了问题与longjmp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用longjmp来模拟goto指令。我有一个包含结构类型(int,float,bool,char)元素的数组DS。我想跳转到labledlablex的地方,其中x是DS [TOP] .int_val。如何处理此问题?

I want to use longjmp to simulate goto instruction.I have an array DS containing elements of struct types (int , float, bool ,char). I want to jump to the place labled "lablex" where x is DS[TOP].int_val. how can I handle this?

示例代码:

...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_buf *) s.str();
longjmp(*bfj,1);

但是我认为它有问题,我该怎么办?

but as I thought it's having problem what should I do?

错误:

output.cpp:在函数'int main()'中:

output.cpp: In function ‘int main()’:

output.cpp:101:error:invalid cast from type'std :: basic_string,std :: allocator>'to type'__jmp_buf_tag(*)[1]'

output.cpp:101: error: invalid cast from type ‘std::basic_string, std::allocator >’ to type ‘__jmp_buf_tag (*)[1]’

推荐答案

你可能不想使用longjmp,但我讨厌它,当人们回答一个问题为什么要这样做?如您所指出的,您的 longjmp()使用方式有误。下面是一个如何正确使用它的简单例子:

You probably don't want to use longjmp at all but I hate it when people answer a question with "Why would you want to do that?" As has been pointed out your longjmp() usage is wrong. Here is a simple example of how to use it correctly:

#include <setjmp.h>

#include <iostream>

using namespace std;

jmp_buf jumpBuffer;  // Declared globally but could also be in a class.

void a(int count) {
  // . . .
  cout << "In a(" << count << ") before jump" << endl;
  // Calling longjmp() here is OK because it is above setjmp() on the call
  //   stack.
  longjmp(jumpBuffer, count);  // setjump() will return count
  // . . .
}


void b() {
  int count = 0;

  cout << "Setting jump point" << endl;
  if (setjmp(jumpBuffer) == 9) return;
  cout << "After jump point" << endl;

  a(count++);  // This will loop 10 times.
}


int main(int argc, char *argv[]) {
  b();

  // Note: You cannot call longjmp() here because it is below the setjmp() call
  //  on the call stack.

  return 0;
}

您对longjmp()的使用问题如下:

The problems with your usage of longjmp() are as follows:


  1. 您不调用setjmp()

  2. 您尚未在堆栈上分配jmp_buf,动态。 jmp_buf * bfj 只是指针。

  3. 您不能将 char * 强制转换为 jmp_buf * 期望它工作。 C ++不是动态语言,它是静态编译的。

  1. You don't call setjmp()
  2. You haven't allocated the jmp_buf either on the stack or dynamically. jmp_buf *bfj is just a pointer.
  3. You cannot cast a char * to jmp_buf * and expect it to work. C++ not a dynamic language it is statically compiled.

但实际上,你不应该使用 longjmp )

But really, it is very unlikely that you should be using longjmp() at all.

这篇关于问题与longjmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆