Converting vba to vb.net getting error with a function

zuccj

New member
Joined
Feb 5, 2018
Messages
1
Programming Experience
1-3
I have a program that was created in vba, and I am working on converting it to VB.net. I have managed to get most of it working, but I am having issues with converting one function right now.
The function in vba is:

VB.NET:
Private Function OpenPort(CommPort As Integer, CommSettings As String) As LongPtr

    Dim CommDCB As DCB
    Dim status As Long
    Dim Handle As LongPtr
    Dim timeOuts As commTimeOuts
      
    ' Open port
    Handle = CreateFile("\\.\COM" + Trim(Str(CommPort)), &HC0000000, 0, Null, 3, &H80, 0)
    MsgBox (Handle)
    If Handle = -1 Then
        OpenPort = -1
    Else
    
        'Try to apply settings to the port
        status = GetCommState(Handle, CommDCB)
        If status = 0 Then
            ClosePort (Handle)
            OpenPort = -1
            Exit Function
        End If
        
        status = BuildCommDCB(CommSettings, CommDCB)
        If status = 0 Then
            ClosePort (Handle)
            OpenPort = -1
            Exit Function
        End If
        
        status = SetCommState(Handle, CommDCB)
        If status = 0 Then
            ClosePort (Handle)
            OpenPort = -1
            Exit Function
        End If
        
        With timeOuts
            .ReadIntervalTimeout = -1
            .ReadTotalTimeoutMultiplier = 0
            .ReadTotalTimeoutConstant = 500
            .WriteTotalTimeoutMultiplier = 0
            .WriteTotalTimeoutMultiplier = 500
        End With
        
        status = SetCommTimeouts(Handle, timeOuts)
         If status = 0 Then
            ClosePort (Handle)
            OpenPort = -1
            Exit Function
        End If
        
        OpenPort = Handle
        
    End If
    
End Function

The error I am getting with the changes to make it work in vb.net is "System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'"
The error is on the line

VB.NET:
status = Relay_Functions.GetCommState(Handle, CommDCB)

I have changed the line to create the handle as such:

VB.NET:
Handle = Relay_Functions.CreateFile("\\.\COM" + Trim(Str(CommPort)), &HC0000000, 0, Nothing, 3, &H80, 0)

I have changed the longs to integers as well throughout the function as well. I'm thinking the error is with Trim(Str(CommPort)), but I'm not fully sure that is correct, as I haven't been able to get anything that doesn't throw the error and have it work correctly yet.
 
Back
Top