简体   繁体   English

C#Pinvoke免费本机C ++内存

[英]C# pinvoke free native c++ memory

If i have a c++ function which returns a char* like this: 如果我有一个c ++函数,它返回一个char *像这样:

char *cctalk_app_event_name(DG_CCTALK_APP_EVT_CODE);

And the corresponding C# signature: 以及相应的C#签名:

[System.Runtime.InteropServices.DllImportAttribute("cctalk.dll", EntryPoint = "cctalk_app_event_name", CallingConvention = CallingConvention.Cdecl)]
    public static extern System.IntPtr cctalk_app_event_name(DG_CCTALK_APP_EVT_CODE param0);

If the native code returns a char* allocated with the new keyword, i am for sure gonna have a memleak each time i call this function C#? 如果本机代码返回分配有new关键字的char *,我确定每次调用C#函数时都会有memleak吗? Is there a way i can free that memory? 有什么办法可以释放内存吗?

My hunch from looking at the function name is that this may well be returning a pointer to a string constant within the DLL, in which case you don't need to worry about freeing the pointer anyway. 我对函数名的直觉是,这很可能是返回指向DLL中字符串常量的指针,在这种情况下,您不必担心会释放指针。

If the manual for the SDK ( link here ) wasn't any use, then I'd disassemble the DLL and look at what that function did, but don't worry about how to delete it before you've established that you need to. 如果没有使用SDK的手册( 此处的链接 ),那么我将反汇编DLL并查看该函数的作用,但是不必担心在确定需要删除它之前如何删除它。 。

If you don't have any documentation or source then you cannot know whether or not the memory was allocated with new. 如果您没有任何文档或资料,那么您将不知道是否为内存分配了新的内存。 If it was allocated with new then it needs to be deallocated with delete. 如果使用new分配,则需要使用delete取消分配。 That can only be done from the native code. 这只能通过本机代码完成。 If that is needed then the DLL will need to export a deallocator for you. 如果需要,则DLL将需要为您导出一个解除分配器。

Other possibilities include allocation from a shared heap, eg the COM heap. 其他可能性包括从共享堆(例如COM堆)进行分配。 Not very likely. 不太可能。 Or perhaps the string is statically allocated and does not need deallocation. 或者,也许字符串是静态分配的,不需要释放。 This final option is usually the case when a functions returns a C string as a return value. 当函数返回C字符串作为返回值时,通常是这种最终选择。 If you had to guess, that's the percentage option. 如果您不得不猜测,那就是百分比选项。 In any case, if there's no way for you to deallocate the string, what else can you do? 无论如何,如果您无法取消分配字符串,您还能做什么?

The only way you can be sure is to have documentation, or source code, or support from the author. 您可以确定的唯一方法是获得文档,源代码或作者的支持。 I appreciate that you want to know the solution, but your only hope are the options listed in the first sentence of this paragraph. 我很高兴您想知道解决方案,但是您唯一的希望是本段第一句中列出的选项。

I find it hard to believe that a library this complex has no documentation. 我很难相信如此复杂的库没有文档。 How did you come by this library? 您是怎么来这个图书馆的? Are you really sure there are no docs? 您真的确定没有文档吗?

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

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