简体   繁体   English

我应该在C#dllimport本机方法调用中为参数释放内存吗?

[英]Should I release a memory for parameters in C# dllimport native method call?

I used native method call in C# with DllImport feature. 我在C#中使用具有DllImport功能的本机方法调用。 I want to know that should I release memory for method paremeters manually in native-side. 我想知道应该在本机端手动释放方法参数的内存。

Currently, I send double[] array to native method, and native method get paretmers as double* type. 当前,我将double []数组发送到本机方法,本机方法将paretmers作为double *类型。 Should I release double* in native method? 我应该以本机方法发布double *吗?

No, you should let .NET handle the memory management itself. 不,您应该让.NET自己处理内存管理。 The native code marshaller follows the basic rules for COM interop, which also happen to work most of the time for P/Invoke, since Win32 also follows the rules. 本地代码编组器遵循COM互操作的基本规则,因为Win32也遵循该规则,所以在大多数情况下P / Invoke都可以使用COM互操作。 (There are exceptions, but they'd be called out in the Windows API documentation). (有一些例外,但是在Windows API文档中会注明)。

Since you wrote both ends of the P/Invoke call, you should follow those same rules to make your life easy. 由于您编写了P / Invoke调用的两端,因此应该遵循相同的规则,以使您的生活变得轻松。 As far as memory allocations are concerned, most of the time the caller is responsible for freeing any memory that crosses the P/Invoke boundary, since the callee doesn't know if/when it's safe to do so. 就内存分配而言,大多数情况下, 调用方负责释放任何跨越P / Invoke边界的内存,因为被调用方不知道是否/何时安全。 This includes: 这包括:

  • If you allocate memory for a parameter and pass it in 如果您为参数分配内存并传递给它
  • If there is an out parameter or return value that is allocated by the callee and returned 如果有被调用者分配并返回的out参数或返回值

In both cases, only the caller knows when the memory is no longer needed and is safe to be freed. 在这两种情况下,只有调用者才能知道何时不再需要该内存并且可以安全地释放它。 In the case of a P/Invoke call, the run-time marshaller knows this, and it will allocate memory to marshal your double[] to a double * before it makes the call, then free that memory when the call returns. 对于P / Invoke调用,运行时编组器知道这一点,它将在调用之前分配内存以将double[]编组为double * ,然后在调用返回时释放该内存。 Depending on the combination of ref , out , [In] or [Out] attributes, it may or may not try to copy the data back into your double[] , but it will always free that memory. 根据refout[In][Out]属性的组合,它可能会或可能不会尝试将数据复制回double[] ,但它始终会释放该内存。

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

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