In this activity, the VB project from 17.3 will be modified to call the TimDLL.dll as developed in the Native Code chapter to get the local time.
As per C# version (17.5 Calling Native Code from C# Managed Code) except (apart from VB-C# normal syntax differences):
In the internal static class PInvoke
< DllImport("TimeDLL.dll") > _ Public Shared Sub GetTime(ByRef timeStr As StringBuilder) End Sub
< DllImport("TimeDLL.dll") > _
Public Shared Sub GetTime(ByRef timeStr As StringBuilder)
End Sub
Imports System.Runtime.InteropServices Imports System.Text Public Class PInvoke End Class
Imports System.Runtime.InteropServices
Imports System.Text
Public Class PInvoke
End Class
Add the following to the PInvoke class:
Add the following reference at the top of the app code:
Modify the TimeButton event handler to:
'Create a StringBuilder object with capacity for 100 characters Dim timeStr as StrinlgBuilder = new StringBuilder(100) 'Call the native code PInvoke.GetTime(timeStr) 'Display the string textBox1.Text = timeStr.ToString( )
'Create a StringBuilder object with capacity for 100 characters
Dim timeStr as StrinlgBuilder = new StringBuilder(100)
'Call the native code
PInvoke.GetTime(timeStr)
'Display the string
textBox1.Text = timeStr.ToString( )
Build and test run the application. A runtime error will be reported that the GetTime entry point couldn't be found in the DLL, if exercise 17.5 hasn't been completed. Refer to 17.5 Step 7 to resolve this. The modified app should now function correctly. Again, the VB app did not need recompilation.
Figure 17.x The Managed Code VB app accessing the native code to get the local time string
NEXT: 17.7 C# Managed Code DLL
Click here to provide feedback and input