In this activity, the call to the native code to generate the local time string, will be actioned by a Callback. The action will be performed both synchronously and asynchronously.
In this segment of the activity, the managed code calls the native code which inturn calls back into the managed code using the method passed to it by the managed code. The instantiated StringBuilder object is passed to the native code, which is embellished with a call to GetTime and then passed back as a parameter to called managed code function. This is all synchronous as the calling managed thread actions all of the processing in sequence.
Add the following to the PInvoke class:
[DllImport("TimeDLL.dll")] public static extern void CallbackGetTime(FunctionPtr pf, StringBuilder value); Listing 17. The PInvoke signature for the native code function, CallbackGetTime( )
Note:
Callbacks are typically used to call Win32 functions where a Callback is required. In these cases the call is made and returns so as to not lockup the UI. Windows then performs the required processing and then calls the provided function in the calling application. Hence these Callbacks are completed asynchronously.
In this segment of the activity, a thread is launched in the native code when it is called by the managed code, and the call returns to the managed code without the result. After a delay, the thread generates the DateTime string, then does the Callback asynchronously and exits. Normally a delay would not be inserted but its used in this case to demonstrate that it is the thread calling back that actions the update. To highlight this, the textbox is cleared before the initial call is made from the managed code.
One issue that has been pointed to, that only UI threads can update a control, is addressed using a standard pattern involving Control.InvokeRequired.
In the ManagedCode project:
When the Callback occurs an error is generated as shown:
This is because, as flagged, a UI thread must update a control. The native code thread actioning the Callback can't do that. There is a standard pattern for doing this as discussed in: http://msdn.microsoft.com/en-us/library/ms171728.aspx. Rather than directly update the Textbox Text property, a function is called. If the thread that calls that function isn't a UI thread then a Delegate is launched as a UI thread to perform that function call so that the update does occur.
NEXT: 17.9 Managed Code Access to Remote Data
Click here to provide feedback and input