繁体   English   中英

Memory 使用 C# 应用程序使用 C++ DLL

[英]Memory usage from C# apps using C++ DLLs

为了正确起见,如果我对调用 C++ dll 的 C# 程序之间的数据流的想象正确,我想听听您的意见

  1. 系统将 memory 给 C# 程序
  2. C# 程序加载.dll 并将其部分空间分配给 C++ Z06416233FE5EC24C593Z.AB8AF14 在这个空间中不会有 C# 垃圾收集,只有当 .dll 被卸载然后才能释放整个空间。
  3. 调用了 C++ function。 特定的 Function 有一个委托作为参数。 我们深入 C++ memory 区域并声明一些变量。 C++ function 将在其代码中的某处调用 C# 代表。
  4. The C# delegate operates on the C# Memory and will have a copy of its input parameters in the C# memory, if they are native types or a reference to the variables in the C++ memory, if it is a complex type. 如果我们有原生类型,我可以将其保存到 C# 世界中,一切都会好起来的。 But if it is a reference and I just save it into my C# memory, I will get undefined behaviour, if I end my C++ function, because the variables will get out of scope and will be destroyed.
  5. The C# function ends and we get the returnvalue in C++ as copy (or a pointer to the returnvalue, if it is a complex type, the pointer will point into the C# memory)
  6. the C++ function ends and the used memory of the C++ function is released

我说得对吗?

这应该在编组器的文档中进行描述

如果它们是本机类型或对 C++ memory 中的变量的引用,如果它是复杂类型。 如果我们有原生类型,我可以将其保存到 C# 世界中,一切都会好起来的。 But if it is a reference and I just save it into my C# memory, I will get undefined behavior, if I end my C++ function, because the variables will get out of scope and will be destroyed

我的理解是编组器会将复杂类型转换为结构或指针(IntPtr)。 结构是按值传递的,因此您将在托管 memory (可能在堆栈上)中有一个副本。 指针需要不安全的代码才能访问,因此您将负责安全地处理它们。

C++ 作为拷贝(或者是指向返回值的指针,如果是复杂类型,指针会指向C#内存)

托管 function 无法以安全的方式返回指向托管 memory 的指针。 要创建指针,您需要修复 object 以防止 GC 移动它,但修复是有范围的,因此它不适用于返回值。

我个人认为编组规则有点复杂,我宁愿保持任何 p/Invoke 简单,如果没有其他原因,只是为了避免有关安全的问题。 对于 c# 和 c++ 之间更复杂的互操作性,我建议使用 c++/cli。 这允许您自己进行类型转换,并添加一整套可用于确保正确运行的工具。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM