使用从VB6到C#的LSet?

时间:2016-03-08 10:29:12

标签: c# vb6 vb6-migration

我目前正在将VB6转换为C#。你能帮我转换一下这段代码吗?

这是VB6代码:

'This converts the bytes into test parameters
Sub getParamValues(ByRef TransData() As Byte, ByRef testparam() As Single, startbyte As Integer)
Dim tmpdata As bByteType
Dim convertedvalue As SingleType
Dim i As Integer
Dim bytecounter As Integer
bytecounter = startbyte

'On Error Resume Next
For i = 0 To 9
    tmpdata.bBytes(0) = TransData(bytecounter + 3) 'TransData(0 + 3)
    tmpdata.bBytes(1) = TransData(bytecounter + 2) 'TransData(0 + 2)
    tmpdata.bBytes(2) = TransData(bytecounter + 1) 'TransData(0 + 1)
    tmpdata.bBytes(3) = TransData(bytecounter)     'TransData (0)

    'THIS CODE I WANT TO CONVERT
    LSet convertedvalue = tmpdata 

    testparam(i) = convertedvalue.dResult 'Gets the test parameters
    bytecounter = bytecounter + 4
Next i
End Sub

和这个

Private Type bByteType
    bBytes(3) As Byte
End Type

Private Type SingleType
    dResult As Single
End Type

我尽力将其转换为C#。但是我得到了NullException。我无法将Type从Vb6转换为C#。所以,我试过struct。但我不知道如何使用C#将bBytes数据传输到tmpdata

public void getParamValues(ref byte[] TransData, ref Single[] testparam, int startbyte) 
    {
        bByteType tmpdata = new bByteType();
        SingleType convertedvalue = new SingleType();
        //byte[] bBytes = new byte[4];
        int bytecounter = 0;
        bytecounter = startbyte;

        for (int i = 0; i < 9; i++)
        {
            tmpdata.bBytes[0] = TransData[bytecounter + 3];
            tmpdata.bBytes[1] = TransData[bytecounter + 2];
            tmpdata.bBytes[2] = TransData[bytecounter + 1];
            tmpdata.bBytes[3] = TransData[bytecounter];
            //LSet convertedvalue = tmpdata <--- Supposed to convert to C#                
            testparam[i] = convertedvalue.dResult;
            bytecounter = bytecounter + 4;
        }
    }

public struct bByteType
    {
         //byte[] bBytes = new byte[3];
        public byte[] bBytes;
        public bByteType(byte[] size)
        {
            bBytes = new byte[4];
        }
    }

    struct SingleType
    {
        public Single dResult;
    }

1 个答案:

答案 0 :(得分:1)

VB6代码交换字节顺序以在big-endian和little-endian之间进行转换。即使结构定义完全不同,VB6中的LSet也会将字节值从一个结构(Type)复制到另一个结构。来自一个变量的二进制数据被复制到另一个变量的存储空间中,而不考虑为元素指定的数据类型。 Gulp!

在C#中执行此操作的最佳方法是something like this answer

在C#中将字节值从一个结构复制到另一个结构要复杂得多 - 例如,您需要将结构固定在内存中以阻止它们在操作的中途移动。