Marshall :: GetFunctionPointerForDelegate: Should I post its result?

I am converting a managed System.Action into an unmanaged std :: function inside a C ++ / CLI project; Should I release this IntPtr after using the callback, or is it not necessary?

void MyClass::Execute(System::Action^ callback) { IntPtr callbackPtr = Marshal::GetFunctionPointerForDelegate(callback); std::function<void (void)> nativeCallback = static_cast<void (__stdcall *) (void)>(callbackPtr.ToPointer()); m_nativeObject->Execute(wrappedCallback); // should I release callbackPtr here? } 
+6
source share
3 answers

No. There is no Marshal class method for this. Like all code that is dynamically generated, the thunk generated by this method is associated with the AppDomain and is unloaded when the AppDomain is unloaded.

Note that this does not apply to the delegate object, it follows the usual rules for garbage collection. And you have to be careful, the trick does not keep him alive. What is the error in your code, the delegate can be assembled when the native code is busy. You need to add this line of code to the end of the method:

 GC::KeepAlive(callback); 

With the assumption that the callback will only be executed as long as the Execute () method is executed. If unmanaged code stores a function pointer outside of this method call, you need to save the delegation object somewhere so that it is right.

+6
source

No, but if you called Alloc to create a GCHandle in the callback delegate, you must free this handle with GCHandle.Free (). Here is a good article, including how to prevent GC from being prematurely removed from your delegate: http://msdn.microsoft.com/en-us/library/367eeye0%28v=VS.100%29.aspx

+4
source

You will not need to release the pointer. You already have a function pointer (32/64 bit size, depending on your machine architecture). If the .net infrastructure infrastructure needed something more to run the pointer, then this would be the same for all methods, so it would be statically distributed (stateless).

+2
source

Source: https://habr.com/ru/post/944895/


All Articles