我用MFC做了个Regular DLL,其中一个接口形如:
CString GetName(...);
或者:
void GetName(CString &);
应用程序一般这样来调用: CString name = GetName(...);或者GetName(name)
我自己用得好好的,别人使用该DLL的时候居然出现_CrtIsValidHeapPointer的异常,原因在msdn中说得很清楚:
The _CrtIsValidHeapPointer function is used to ensure that a specific memory address is within the local heap. The “local” heap refers to the heap created and managed by a particular instance of the C run-time library. If a dynamically linked library (DLL) contains a static link to the run-time library, then it has its own instance of the run-time heap, and therefore its own heap, independent of the application’s local heap. When _DEBUG is not defined, calls to _CrtIsValidHeapPointer are removed during preprocessing.
原来应用程序使用Use Static linked MFC DLL,而我的DLL是Use Shared MFC DLL,这就造成DLL中heap和应用程序的heap不同,在DLL中malloc出的地址返回到应用程序并被free,所以就ASSERT了。
CString name("足够长度的字符串"); // 如果这样事先分配足够长度,使用GetName(CString &)
//是没有问题的。
根本的解决方法网上都说了:
在dll中返回对象时需要注意: 1。exe端与dll端必须同为debug或release方式,不能交叉 2。run time library必须一致,例如均为Multi-Threaded dll
但我试了试debug版本,只能同时配置为Multi-Threaded dll才行,其他配置都会出错。这是疑问1。还有一点不明,MFC库中也有类似的函数接口,为什么CWnd::GetWindowText(CString &)却没这个问题呢?