Transferring vector of objects between C++ DLL and Cpp/CLI console project

点点圈 提交于 2019-12-10 11:13:51

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/509863/transferring-vector-of-objects-between-c-dll-and-cpp-cli-console-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!