开发者

Checking for Null Bytes

开发者 https://www.devze.com 2023-04-03 14:44 出处:网络
I\'m using Visual Basic .NET to work with a USB HID device. Most of the time, I can receive data from it perfectly... but one out of every thousand transfers or so, my code will think it has received

I'm using Visual Basic .NET to work with a USB HID device.

Most of the time, I can receive data from it perfectly... but one out of every thousand transfers or so, my code will think it has received data when it actually hasn't.

The device writes to an array 开发者_如何学Pythonof bytes. I wanted to check to see if the received packet is empty, by doing something like this:

If myDevice.dataPacket(1) <> Nothing then
    myDevice.rxDataReady = False

Unfortunately, even with this I get a NullReferenceException, saying that the object reference is not set to an instance of an object.

Is there a different way to do this, or should I just handle a NullReferenceException? If I execute this routine hundreds of times a minute, will adding the exception slow things down at all?


So, a couple of things.

  1. A Byte is a value type and therefore can never be null. In VB.Net, when you set or check for Nothing using the equality sign = you are actually setting or checking if the value holds "the default value". For numeric types the "default value" is zero so these two statements are the same:

    If MyByte = Nothing Then ...

    If MyByte = 0 Then ....

  2. Because of the above rule you should never receive a NullReferenceException (NRE) when accessing a byte because a byte cannot be null. However, the thing holding a byte can be null. So in your case you should be checking:

    If myDevice.dataPacket IsNot Nothing Then

  3. Depending on how the bytes within dataPacket are set you might also want to check the dataPacket.Length property (after checking that dataPacket isn't null) to make sure that there are enough indices in the array. If you go outside of the indices you'll get a IndexOutOfRangeException.

    If (myDevice.dataPacket IsNot Nothing) AndAlso (myDevice.dataPacket.Length >= 100) Then


Try changing syntax to this:

If NOT myDevice.dataPacket(1) is Nothing then
    myDevice.rxDataReady = False


Are you initializing it (new)?

myDevice.dataPacket = new List(Of Byte)()
0

精彩评论

暂无评论...
验证码 换一张
取 消