}while(0) extern void list_add_before(list_head *node, list_head *pos); extern void list_add_after(list_head *node, list_head *pos); extern void list_del(list_head *node); #endif #include “list.h” void list_add_before(list_head *node, list_head *pos) { node->prev = pos->prev; node->next = pos; pos->prev->next = node; pos->prev = node; } void list_add_after(list_head *node, list_head *pos) { node->prev = pos; node->next = pos->next; pos->next->prev = node; pos->next = node; } void list_del(list_head *node) { node->prev->next = node->next; node->next->prev = node->prev; } #ifndef EXC_H #define EXC_H char err = -1; static char isJumpListInit = 0; //jmp_buf jump_buffer; typedef struct JumpBufListTag { struct list_head_tag list; jmp_buf jump_buffer; }JumpBufList, *JumpBufListPtr; JumpBufList jumplist = {NULL, NULL}; JumpBufListPtr head = &jumplist; JumpBufListPtr cur = &jumplist; int SetCurJump(void) { JumpBufListPtr newPtr = (JumpBufList*)calloc(sizeof(JumpBufList)); if (!isJumpListInit) { init_list_head(&head->list); isJumpListInit = 1; } list_add_after(&newPtr->list, &head->list); cur = newPtr; return 0; } void JumpCurLong(void) { longjmp(cur->jump_buffer, 1); } void DestoryCurJumpEnv( void ) { list_del(&cur->list); free(cur); cur = head->list.next; } #define try SetCurJump();if(setjmp(cur->jump_buffer) == 0) #define catch(N) DestoryCurJumpEnv();if(N>=0) #define throw(N) err=N;JumpCurLong(); #endif 这边,List.h和list.c摘抄自linux内核代码。 使用demo代码: void h() { throw(7); } void e() { h(); } void g(void) { try { e(); printf(“g()3”); } catch(err) { throw(err); } } int main() { try { g(); } catch(err) { printf(“%d”, err); } return 0; } 这样,就可以实现一个简易版本的用c语言模拟c++的错误处理异常的机制了。 |