VB.net小技巧——VB.net中的结构体和共用体提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 前言
- 结构体和共用体的定义
- 一个完整的程序示例
- 下位机和上位机浮点传输示例
- 下位机示例
- 上位机示例
前言
在C语言中,有一种类型名为共用体,关键字为union,它与结构体十分类似,但是它所有的数值全都指向同一个指针。也就是说,当你修改共用体内的某一个数据时,其他数据也会同时改变。
这个类型的好处,在于可以存储某种不确定的数据对象,等到稍后再来分析出该对象的用途。
这个对于数制的转换和传输非常有用。
在之前的VB6.0中,我使用的是CopyMemory的方法,但在现在的VB.net中这里有了新的变化,在这里记录一下
union MyUnion
{
char b; //单字节整数,在c语言中用char类型来表示单字节整数
short s; //双字节整数
int i; //四字节整数
}
在 .net 中使用联合体,我们只需要声明一个普通的结构体,然后在结构体上使用属性描述即可。
结构体:
Structure MyStruct
Dim b0 As Byte
Dim b1 As Byte
Dim b2 As Byte
Dim b3 As Byte
Dim s As Short
Dim us As UShort
Dim i As Integer
Dim ui As UInteger
End Structure
联合体:
Imports System.Runtime.InteropServices'引入运行时非托管数据管理服务
_
Structure MyUnion
Dim b0 As Byte
Dim b1 As Byte
Dim b2 As Byte
Dim b3 As Byte
Dim s As Short
Dim us As UShort
Dim i As Integer
Dim ui As UInteger
End Structure
可以看出 .NET 中的联合体更强大,因为它甚至可以指定某个数值的偏移位置。
一个完整的程序示例Imports System.Runtime.InteropServices '引入运行时非托管数据管理服务
Public Class Form1
_
Structure MyUnion
Dim b0 As Byte
Dim b1 As Byte
Dim b2 As Byte
Dim b3 As Byte
Dim s As Short
Dim us As UShort
Dim i As Integer
Dim ui As UInteger
Dim fd As Single
End Structure
Structure MyStruct
Dim b0 As Byte
Dim b1 As Byte
Dim b2 As Byte
Dim b3 As Byte
Dim s As Short
Dim us As UShort
Dim i As Integer
Dim ui As UInteger
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mu As MyUnion
' 一种安全的int与uint转换方法
'mu.ui = UInteger.MaxValue
mu.i = &H8234567F
mu.ui = &H7234567F
MsgBox(mu.i)
' 一个存储与读取IP数据的方法
mu.b0 = 128 : mu.b1 = 0 : mu.b2 = 0 : mu.b3 = 1 '127.0.0.1
Dim ip As New Net.IPAddress({128, 0, 0, 1})
MsgBox(CInt(ip.GetHashCode) = mu.i) 'ip数值相等
' 其他用法...
mu.ui = UInteger.MaxValue
MsgBox(mu.s) '-1
MsgBox(mu.us) '65535
End Sub
End Class
下位机和上位机浮点传输示例
如果下位机和上位机是通过串口传输
下位机示例union DoubleToBit
{
unsigned char char_buffer[8];
double double_num;
};
union FloatToBit
{
unsigned char char_buffer[4];
float float_num;
};
void transFloat(float f_ptr)
{
int i;
unsigned char data;
Float_char_union.float_num = f_ptr;
for(i = 0 ; i < 4 ; i++)
{
data = Float_char_union.char_buffer[3-i];
write_queue_tx(data);
}
}
void transDouble(double d_ptr)
{
int i;
unsigned char data;
Double_char_union.double_num = d_ptr;
for(i = 0 ; i < 8 ; i++)
{
data = Double_char_union.char_buffer[7-i];
write_queue_tx(data);
}
}
上位机示例
Imports System.Runtime.InteropServices '引入运行时非托管数据管理服务
Public Class Form1
_
Structure MyUnion
Dim b0 As Byte
Dim b1 As Byte
Dim b2 As Byte
Dim b3 As Byte
Dim fd As Single
End Structure
Dim mu As MyUnion
mu.b0 = hex1
mu.b1 = hex2
mu.b2 = hex3
mu.b3 = hex4
MsgBox(mu.fd)



