Compact 2013 Ebook

17.6 VB P/Invoke
Created by djones on 6/28/2013 8:28:31 AM

Calling Native Code from VB Managed Code

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.

What is required:

  • 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

      • The signature is:
            < DllImport("TimeDLL.dll") > _
        
            Public Shared Sub GetTime(ByRef timeStr As StringBuilder)
        
            End Sub
    • Also need Import reference: Imports System.Runtime.InteropServices in both of the PInvoke class code.

Implementation

  1. Again use the DLL from 14.8. This time start with the VB application from 17.3 

    Next add a class which will encapsulate the native code in the VB application:
  2. Add a class to the application, call it PInvoke
    App project context (Right-click on the app in Solution Explorer)—>Add Class
    Code it as follows:
    Imports System.Runtime.InteropServices
    
    Imports System.Text
    
    Public Class PInvoke
    
    End Class
  3. Add the following to the PInvoke class:

        < DllImport("TimeDLL.dll") > _
    
        Public Shared Sub GetTime(ByRef timeStr As StringBuilder)
    
        End Sub
    Note the line extender at the end of the first line.
  4. Add the following reference at the top of the app code:

    Imports System.Text
  5. 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( )
    
  6. 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.

    image
    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

      print

      Click here to provide feedback and input

        Comments

      There is no comment.

      Turkish porno izle video site in rokettubeporno izle