簡體   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