tags:

views:

849

answers:

4

Hi,

I have a C++ library app which talks to a C++ server and I am creating a vector of my custom class objects. But my Cpp/CLI console app(which interacts with native C++ ), throws a memory violation error when I try to return my custom class obj vector.

Code Sample -

In my native C++ class -

std::vector<a> GetStuff(int x)
{
   -- do stuff
   std::vector<a> vec;
   A a;
   vec.push_back(a);
--- push more A objs
   return vec;
}

In my Cpp/CLI class

public void doStuff()
{
   std::vector<a> vec;
   vec = m_nativeCpp->GetStuff(4);   // where nativeCpp is a dynamically allocated class in nativecpp DLL, the app throws up a memory violation error here!
}

exact error message - An unhandled exception of type 'System.AccessViolationException' occurred in CLIConsole.exe -- which is my console cpp/CLI project

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Anything I am missing here ?What should be the ideal way to return such an array -

Regards Amit

A: 

I'm not sure, but this may work: instead of returning a vector, create the vector on the heap and return a pointer to it.

Frederick
Just from the C++ side of things, this won't help. The routine as written is already returning a copy of the vector.
Harper Shelby
+2  A: 

Take a look at this support article. I think what's happening is that your vector in CLI tries to access internal vector data from DLL and fails to do so because of different static variables. I guess the only good solution is to pass simple array through DLL boundaries, &vector[0] returns it.

But there might be also some magic happening in A class copy constructors. If they missing and class have pointers as members you could easily get the same error.

vava
+1  A: 

I'll assume that the native code is in a separately compiled unit, like a .dll. First thing the worry about is the native code using a different allocator (new/delete), you'll get that when it is compiled with /MT or linked to another version of the CRT.

Next thing to worry about is STL iterator debugging. You should make sure both modules were compiled with the same setting for _HAS_ITERATOR_DEBUGGING. They won't be the same if the native code was built with an old version of the CRT of is the Release mode build.

Hans Passant
A: 

Hey Amit

were u able to solve ur problem? I am facing the same problem.. cant find a solution for it... i know the error happens when the cli/c++ tries to destroy the vector object...

hari