使用内部try catch来防止C ++ DLL异常 [英] Prevent C++ DLL exception using try catch internally

查看:1042
本文介绍了使用内部try catch来防止C ++ DLL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个C ++ DLL,为主应用程序分配一个数组。
该函数返回一个错误代码,而不是指向新创建的数组的指针,因此第一个成员的地址将被写入函数的一个参数。
示例:

  int foo(int ** arrayPtr){
int * array = new int [ 10];
* arrayPtr = array;
return 0;
}

因此,在main中我调用函数:

  int * myArray; 
int ret;
ret = foo(& myArray);

现在myArray指向新创建的数组。



问题1:有更好的方法吗?



比这个更有趣的问题。
如果我传递NULL作为foo的参数,我会生成一个Access Violation异常,因为

  * arrayPtr = array; 

将尝试写入0x00000。



所以,我添加了一个try-catch块

  int foo(int ** arrayPtr){
int * array = new int [10];
try {
* arrayPtr = array;
} catch(...){
return 1;
}
return 0;
}



我希望,当我使用NULL作为参数调用foo时,不是真的!它会产生一个异常。



问题2:为什么DLL中的try-catch块不起作用?



感谢大家!



PS:使用try-catch直接在主体中生成相同的异常不会生成异常(或更好, try-catch块)。

解决方案


  1. 。只要确保公开一个函数来删除通过调用foo分配的内存块(以防你的dll使用不同于主应用程序的CRT)。


  2. 访问冲突不应该抛出C ++异常,尽管在VC ++中有一些设置会使SEH异常映射到C ++异常。这通常被认为是一个坏主意。


I'm developing a C++ DLL that allocate an array for the main application. The function return an error code and not the pointer to the new created array, so the address of the first member will be written in a parameter of the function. Example:

int foo(int** arrayPtr) {
  int* array = new int[10];
  *arrayPtr = array;
  return 0;
}

So, in the main I call the function that way:

int* myArray;
int ret;
ret = foo(&myArray);

Now myArray points to the new created array.

QUESTION 1: Is there a better way to do this?

Than the more interesting question. If I pass NULL as parameter for foo, I generate an Access Violation exception because

*arrayPtr = array;

will try to write in 0x00000.

So, I added a try-catch block

int foo(int** arrayPtr) {
  int* array = new int[10];
  try {
    *arrayPtr = array;
  } catch(...) {
    return 1;
  }
  return 0;
}

I expect that , when I call foo with NULL as parameter, it will return 1. Not true! It generate an exception.

QUESTION 2: Why the try-catch block in the DLL doesn't work?

Thanks to everyone!

P.S.: using try-catch for generating the same exception directly in the main doesn't generate an exception (or better, it's correctly handled by the try-catch block).

解决方案

  1. That's pretty much the way to do it. Just be sure to expose a function to delete the memory block allocated by calls to "foo" (just in case your dll uses a different CRT than the main app).

  2. Access violations are not supposed to throw C++ exceptions, although there is some setting in VC++ that would make a SEH exception to be mapped to a C++ one, which is generally considered a bad idea.

这篇关于使用内部try catch来防止C ++ DLL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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