我有一个 C++ 库应用程序,它与 C++ 服务器通信,并且我正在创建自定义类对象的 vector 。但是当我尝试返回自定义类 obj vector 时,我的 Cpp/CLI 控制台应用程序(与 native C++ 交互)会引发内存冲突错误。
代码示例 -
在我的原生 C++ 类中 -
std::vector<a> GetStuff(int x)
{
-- do stuff
std::vector<a> vec;
A a;
vec.push_back(a);
--- push more A objs
return vec;
}
在我的 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!
}
确切的错误消息
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.
最佳答案
我假设 native 代码位于单独编译的单元中,例如 .dll。首先要担心的是使用不同分配器(new/delete)的 native 代码,当它使用/MT 编译或链接到另一个版本的 CRT 时,您会发现这一点。
接下来要担心的是 STL 迭代器调试。您应该确保两个模块都使用相同的 _HAS_ITERATOR_DEBUGGING 设置进行编译。如果 native 代码是使用旧版本的 CRT 或 Release模式构建的,则它们不会相同。
关于c++ - 在 C++ DLL 和 Cpp/CLI 控制台项目之间传输对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/509863/