exe中的内存空闲错误在DLL中分配 [英] the memory free error in exe while is allocated in DLL

查看:77
本文介绍了exe中的内存空闲错误在DLL中分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主机exe加载一个DLL并在其中调用一个函数,该函数返回一个在堆上分配的内存并返回指向主机exe的指针。当释放内存时。这将是一个错误。

The host exe load a DLL and invloke a function in it,The function return a memory allocated on heap and return the pointer to host exe.when the deallocated the memory.It will be a error.

DLL
void DoSth(int *& pInt){
  pInt =new int[10];
}

Exe

void Main(){
  int * pArray=0;
  // invoke the DLL function
  DoSth(pArray);
  //this line will error 
  delete[] pArray;
}





我使用VS2008 SP1。 Windows 7 32位。



有什么问题?



I use VS2008 SP1. windows 7 32bit.

What's the problem?

推荐答案

我一直坚持记忆分配和删除应在同一执行单元中进行。这允许您在问题发生之前解决许多问题。您可以运送DLL并在混合调试/发布环境中使用它,您可以混合编译器和编译器版本,您可以混合语言。你可以从C或Fortran调用你的C ++代码。



使用这种技术的方法是将你的数组放在一个类中,并提供分配和删除API。类,以公共访问方式导出。如果您想使用非OOP语言来调用代码,请导出调用类中创建/删除代码的短存根函数。



有几个概念这里没有一个非常复杂或复杂。
I have always held the practice that "memory allocation and deletion shall occur in the same execution unit." This allows you to solve a number of issues before they happen. You can "ship" a DLL and use it in mixed debug/release environments, you can mix compilers and compiler versions and you can mix languages. You can call your C++ code from C or Fortran.

The way to use this technique is to put your array in a class, and provide allocation and deletion APIs in the class, exported with public access. If you want to use a non-OOP language to call the code, export short stub functions that call the create/delete code in the class.

There are several concepts here but none are terribly complicated or complex.


这篇关于exe中的内存空闲错误在DLL中分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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