[英]Memory usage from C# apps using C++ DLLs
Just to get it right, I would like to have your opinion if I am right with my imagination of how the dataflow is between a C# programm calling a C++ dll with delegates as parameter.为了正确起见,如果我对调用 C++ dll 的 C# 程序之间的数据流的想象正确,我想听听您的意见
Am I right with this?我说得对吗?
This should be described in the documentation for the marshaller这应该在编组器的文档中进行描述
if they are native types or a reference to the variables in the C++ memory, if it is a complex type.如果它们是本机类型或对 C++ memory 中的变量的引用,如果它是复杂类型。 If we have native types I can just save it into the C# world and all will be fine.如果我们有原生类型,我可以将其保存到 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 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
My understanding is that the marshaller will either convert complex types to structs, or pointers (IntPtr).我的理解是编组器会将复杂类型转换为结构或指针(IntPtr)。 Structs are passed by value, so you would have a copy in managed memory (probably on the stack).结构是按值传递的,因此您将在托管 memory (可能在堆栈上)中有一个副本。 Pointers would need unsafe code to access, so you would be responsible for handling these safely.指针需要不安全的代码才能访问,因此您将负责安全地处理它们。
C++ as copy (or a pointer to the returnvalue, if it is a complex type, the pointer will point into the C# memory) C++ 作为拷贝(或者是指向返回值的指针,如果是复杂类型,指针会指向C#内存)
There is not really a way a managed function can return a pointer to managed memory in a safe way.托管 function 无法以安全的方式返回指向托管 memory 的指针。 To create a pointer you would need to fix the object to preventing the GC from moving it, but fixing is scoped, so it would not work for return values.要创建指针,您需要修复 object 以防止 GC 移动它,但修复是有范围的,因此它不适用于返回值。
I personally consider the marshalling rules a bit complicated, and I would prefer to keep any p/Invoke simple, if for no other reason than to avoid questions about safety.我个人认为编组规则有点复杂,我宁愿保持任何 p/Invoke 简单,如果没有其他原因,只是为了避免有关安全的问题。 For more complicated interoperability between c# and c++ I would suggest c++/cli.对于 c# 和 c++ 之间更复杂的互操作性,我建议使用 c++/cli。 This allow you to do type conversion yourself, and adds a whole host of tools you can use to ensure correct functioning.这允许您自己进行类型转换,并添加一整套可用于确保正确运行的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.