C++ DLL returning pointer to std::list

2019-07-21 15:31发布

问题:

I got a dll with the following prototype:

DLL_EXPORT std::list<std::wstring>* c_ExplodeWStringToList(std::wstring in_delimiter, std::wstring in_string, int in_limit);

The application uses this like that:

std::list<std::wstring>* exploded = mydllclass->c_ExplodeWStringToList(L" ", in_command.c_str(), 0);

This works great under XP 32, but when I try this at home with my Vista 64 my program just closes itself. No error and no warning?

Some days ago the DLL was returning the list directly - no pointer. But I switched to VC++ 2010 Express, and I could not compile my DLL without this modification.

Anything I am not seeing here?

Thank you :)

Update:

DLL_EXPORT std::list<std::wstring>* c_ExplodeWStringToList(std::wstring in_delimiter, std::wstring in_string, int in_limit)
{
 std::list<std::wstring>* returnlist = new std::list<std::wstring>();
 std::list<std::wstring>* stringlist = new std::list<std::wstring>();
 UINT pos = 0;

 while(true)
 {
      pos = in_string.find(in_delimiter, 0);

      if(pos == std::string::npos)
      {

           stringlist->push_back(in_string.substr(0, pos));
           break;
      }
      else
      {

           stringlist->push_back(in_string.substr(0, pos));
           in_string = in_string.substr(pos + in_delimiter.length());
      }
 }

 // ****
// Here is missing some code I've commented out while searching for the error.
 // ****
returnlist = stringlist;

return returnlist;
}

T

回答1:

I didn't dig into the code, but a conclusion I came to regarding working with DLLs is to not return anything but primitive types from DLL functions. This is because due to different compilers or different switches or project settings structs and classes are not aligned the same not have the same size in the DLL and in the code calling the DLL.

So returning a list from a DLL might be considered malformed in the caller application.

Same thing regards throwing exceptions from a DLL - the class thrown might be misinterpreted by the catching code.

So, best is export only C functions that return primitive types (to denote error codes).