程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> Variant類型在各語言中的參數傳遞

Variant類型在各語言中的參數傳遞

編輯:.NET實例教程

幾年前我用VB開發了一個西門子PPI通信控件,由於VB開發的控件是標准的COM組件,所以想當然的認為VCC#、Delphi等開發語言可以非常容易的使用。

前段時間由於該控件基於微軟的MSCOMM控件,這個控件如果系統沒有安裝VB,單獨注冊好像很難成功,這害的一些沒有裝VB的用戶,為了這個小控件必須安裝一次VB,這實在是劃算不來,所以直接用API串口函數進行了封裝改進,這樣不僅效率提高了,並且再也不需要MSCOMM控件了。

這一次,我不僅使該控件支持了浮點運算,並且在VC、C#(VB當然就不用多試了,以前就很好的支持)進行了兼容測試。

一試問題就來了,沒有改進之前的控件,由於C#封裝性能甚好,還能使用,唯一不足的是,控件方法中如果不要求返回的參數前面沒有添加ByVal參數,在C#中就轉換為 ref ***,害的你還得專門定義臨時變量進行傳參。

在VC中直接就不行,ReadData和WriteData等幾個主要方法根本在VC中無法轉換成對應函數,具體錯誤信息如下:

// method ''ReadData'' not emitted because of invalid return type or parameter type

// method ''WriteData'' not emitted because of invalid return type or parameter type

// method ''PlcLogin'' not emitted because of invalid return type or parameter type

// method ''PlcRun'' not emitted because of invalid return type or parameter type

// method ''PlcStop'' not emitted because of invalid return type or parameter type

經過測試,最後發現VB函數中的byte和數組在VC中根本找不到合適的對應。

由於控件中又新添加了浮點數的支持,所以對參數接口又增加了一層復雜性。突然想到微軟的MSCOMM控件各語言肯定都能很好的支持,它的接口參數是怎樣的定義的。我在VB、VC、C#分別試了一下,VB中和input和Output屬性的類型就是Variant類型,在VC中是VARIANT,在C#中是Object。用Variant還有個好處,就是各種類型的數據都可以傳輸,沒有必要在另外添加接口函數了。

最後我定義的接口如下(主要接口):

Public Function ReadData(ByVal lngAddr As Long, vData As Variant, Optional ByVal lngNum As Long = 1, Optional ByVal bytLen As PPILEN = PPI_B, Optional ByVal bytType As PPITYPE = PPI_V, Optional ByVal Addr As Long = 0) As Long

Public Function WriteData(ByVal lngAddr As Long, ByVal vData As Variant, Optional ByVal lngNum As Long = 1, Optional ByVal bytLen As PPILEN = PPI_B, Optional ByVal bytType As PPITYPE = PPI_V, Optional ByVal Addr As Long = 0) As Long

 

在VC中對應的接口如下:

long ReadData(long lngAddr, VARIANT* vData, long lngNum, long bytLen, long bytType, long Addr);

long WriteData(long lngAddr, const VARIANT& vData, long lngNum, long bytLen, long bytType, long Addr);

 

在C#中的接口如下:

     public virtual int ReadData(int lngAddr, ref object vData);

     public virtual int ReadData(int lngAddr, ref object vData, int lngNum, PPILEN bytLen, PPITYPE bytType, int addr);

       public virtual int WriteData(int lngAddr, object vData);

   public virtual int WriteData(int lngAddr, object vData, int lngNum, PPILEN bytLen, PPITYPE bytType, int addr);以為這樣定義就萬事大吉了,事後一試我又錯了,在C#中沒有任何問題(看了微軟還是在C#上下了很大的功夫),在VC簡單的定義一個VARIANT變量直接傳遞給控件,VB控件老是報錯,根本無法使用。後來想為什麼MSCOMM控件可以,我的控件不可以。天殺的MSCOMM肯定是VC開發的,而我的控件是VB開發的,VB和C#的包容性都很強,而VC卻高高在上不肯屈就。

正一籌莫展准備放棄的時候,突然想到了以前用VC開發的OPC程序,上面有很多關於VARIANT的應用,一看就明白了,原來在VC中VARIANT的用法是有講究的。

下面我就詳細說一下控件同樣的接口在不同語言中如何使用。

在VB中:

Private Sub cmdReadData_Click()

    On Error GoTo ToExit ''打開錯誤陷阱

    ''------------------------------------------------

    Dim i As Long

    Dim bytType As Byte

    Dim lngRet As Long

    Dim lngData() As Long

    Dim fData() As Single

    Dim vData As Variant

 

    Select Case cmbType.ListIndex

    Case 0: bytType = PPI_I

    Case 1: bytType = PPI_Q

    Case 2: bytType = PPI_M

    Case 3: bytType = PPI_V

    Case 4: bytType = PPI_S

    Case 5: bytType = PPI_SM

    End Select

 

    S7_PPI1.FixAddr = cmbNo.ListIndex + 1

    lngRet = S7_PPI1.ReadData(Val(txtAddr), vData, Val(cmbNum.Text), Val(cmbLen.ListIndex), Val(bytType))

    If lngRet = 0 Then

        txtData = ""

        If cmbLen.ListIndex = 3 Then

            fData = vData

            For i = 1 To Val(cmbNum.Text)

                txtData = txtData & Format(fData(i - 1), "0.00") & " "

            Next

        Else

            lngData = vData

            For i = 1 To Val(cmbNum.Text)

                txtData = txtData & Format(lngData(i - 1), "0") & " "

            Next

        End If

    Else

        txtData = "Error"

    End If

 

    ''------------------------------------------------

    Exit Sub

    ''----------------

ToExit:

    MsgBox Err.Description

End Sub

Private Sub cmdWriteData_Click()

    On Error GoTo ToExit ''打開錯誤陷阱

    ''------------------------------------------------

    Dim bytType As Byte

    Dim strData() As String

    Dim lngRet As Long

    Dim lngData(100) As Long

    Dim fData(100) As Single

    Dim i As Long 

    Select Case cmbType.ListIndex

    Case 0: bytType = PPI_I

    Case 1: bytType = PPI_Q

    Case 2: bytType = PPI_M

    Case 3: bytType = PPI_V

    Case 4: bytType = PPI_S

    Case 5: bytType = PPI_SM

    End Select

 

    If Len(txtData) > 0 Then

        strData = Split(txtData, " ")

        If cmbLen.ListIndex = 3 Then

            For i = 0 To UBound(strData)

                fData(i) = Val(strData(i))

            Next

            lngRet = S7_PPI1.WriteData(Val(txtAddr), fData, UBound(strData) + 1, Val(cmbLen.ListIndex), Val(bytType), cmbNo.ListIndex + 1)

        Else

            For i = 0 To UBound(strData)

                lngData(i) = Val(strData(i))

            Next

            lngRet = S7_PPI1.WriteData(Val(txtAddr), lngData, UBound(strData) + 1, Val(cmbLen.ListIndex), Val(bytType), cmbNo.ListIndex + 1)

        End If

 

        If lngRet = 0 Then

            ''

        Else

            txtData = "Error"

        End If

    End If

    ''------------------------------------------------

    Exit Sub

    ''----------------

ToExit:

    MsgBox Err.Description

End Sub

 

在C#中:

/// <summary>

        /// 讀數據

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnRead_Click(object sender, EventArgs e)

        {

            int intAddr = int.Parse(txtFixAddr.Text);

            object vData = new object();

          

            /*

            [PPI_I] = &H81

            [PPI_Q] = &H82

            [PPI_M] = &H83

            [PPI_V] = &H84

            [PPI_S] = 4

            [PPI_SM] = 5

            */

            PPIV2.PPITYPE DataType= PPIV2.PPITYPE.PPI_V;

            switch (cmbDataType.SelectedIndex)  //數據類型

     &n  {

                case 0:

                    DataType = PPIV2.PPITYPE.PPI_I;

                    break;

                case 1:

                    DataType = PPIV2.PPITYPE.PPI_Q;

                    break;

                case 2:

                    DataType = PPIV2.PPITYPE.PPI_M;

                    break;

                case 3:

                    DataType = PPIV2.PPITYPE.PPI_V;

                    break;

                case 4:

                    DataType = PPIV2.PPITYPE.PPI_S;

                    break;

                case 5:

                    DataType = PPIV2.PPITYPE.PPI_SM;

                    break;

            }

            if (axS7_PPI1.ReadData(int.Parse(txtDataAddr.Text), ref vData, cmbLen.SelectedIndex+1  , (PPIV2.PPILEN)cmbDataMode.SelectedIndex, DataType, intAddr) == 0)

            {

                if (cmbDataMode.SelectedIndex == 3)

                {

                    float[] fData = (float[])vData;                    txtData.Text = "";

                    for (int i = 0; i < fData.Length; i++)

                    {

                        txtData.Text += fData[i].ToString("0.00") + " ";

                    }

                }

                else

                {

                    Int32[] intData = (Int32[])vData;

                    txtData.Text = "";

                    for (int i = 0; i < intData.Length; i++)

                    {

                        txtData.Text += intData[i].ToString() + " ";

                    }

                }

            }

            else

            {

                txtData.Text = "ERROR";

            }

        }

 

        /// <summary>

        /// 寫數據

        /// </summary>

        /// <param name="sender"></param>

/// <param name="e"></param>

        private void btnWrite_Click(object sender, EventArgs e)

        {        

 

            int intAddr = int.Parse(txtFixAddr.Text);

            object vData = new object();

 

            /*

            [PPI_I] = &H81

            [PPI_Q] = &H82

            [PPI_M] = &H83

            [PPI_V] = &H84

            [PPI_S] = 4

            [PPI_SM] = 5

            */

            PPIV2.PPITYPE DataType = PPIV2.PPITYPE.PPI_V;

            switch (cmbDataType.SelectedIndex)  //數據類型

            {

                case 0:

                    DataType = PPIV2.PPITYPE.PPI_I;

                    break;

                case 1:

                    DataType = PPIV2.PPITYPE.PPI_Q;

                    break;

                case 2:

                    DataType = PPIV2.PPITYPE.PPI_M;

                    break;

                case 3:                    DataType = PPIV2.PPITYPE.PPI_V;

                    break;

                case 4:

                    DataType = PPIV2.PPITYPE.PPI_S;

                    break;

                case 5:

                    DataType = PPIV2.PPITYPE.PPI_SM;

                    break;

            }

            long lngRet = 0;

            if (cmbDataMode.SelectedIndex == 3)

            {

                float[] fData = new float[100];

                fData[0] = float.Parse(txtData.Text);

                lngRet = axS7_PPI1.WriteData(int.Parse(txtDataAddr.Text), fData, 1, (PPIV2.PPILEN)cmbDataMode.SelectedIndex, DataType, intAddr);

            }

            else

            {

                Int32[] intData = new Int32[100];

                intData[0] = Int32.Parse(txtData.Text);

                lngRet = axS7_PPI1.WriteData(int.Parse(txtDataAddr.Text), intData, 1, (PPIV2.PPILEN)cmbDataMode.SelectedIndex, DataType, intAddr);

            }

            if (lngRet != 0)

            {

                txtData.Text = "ERROR";          }

        }

 

在VC中:

//讀數據

void CPPI_TestDlg::OnReadData()

{

       //pCombo->GetLBText (pCombo->GetCurSel (), strType);

       long lngFixAddr=0,lngDataAddr=0;

       char strAddr[255];

       m_FixAddr.GetWindowText(strAddr,255);

       sscanf(strAddr,"%ld",&lngFixAddr);

      

       m_DataAddr.GetWindowText(strAddr,255);

       sscanf(strAddr,"%ld",&lngDataAddr);

    /*

       [PPI_I] = &H81

    [PPI_Q] = &H82

    [PPI_M] = &H83

    [PPI_V] = &H84

    [PPI_S] = 4

    [PPI_SM] = 5

       */

    long DataType;

       switch (m_DataType.GetCurSel())  //數據類型

       {

       case 0:

              DataType=0x81; 

              break;

       case 1:

DataType=0x82;

              break;

       case 2:

              DataType=0x83;

              break;

       case 3:

              DataType=0x84;

              break;

       case 4:

              DataType=0x4;

              break;

       case 5:

              DataType=0x5;

              break;

       }

 

       long lngRet;

    VARIANT vData;

       VariantInit (&vData);

       if(m_DataMode.GetCurSel()==3)  //浮點數

       {

           vData.vt = VT_R4 | VT_ARRAY;

           vData.parray=SafeArrayCreateVector(VT_R4, 0, 255 );    

       }

       else

       {

           vData.vt = VT_I4 | VT_ARRAY;

           vData.parray=SafeArrayCreateVector(VT_I4, 0, 255 );     //SAFEARRAY vd;

       }   

       lngRet=m_PPI.ReadData(lngDataAddr,&vData,m_DataNum.GetCurSel()+1,m_DataMode.GetCurSel(),DataType,lngFixAddr);        if(lngRet==0)

       {

              CString strData;

              if(m_DataMode.GetCurSel()==3)  //浮點數

              {

                     float *fData;

                     SafeArrayAccessData(vData.parray, (void**)&fData );

                     for(int i=0;i<m_DataNum.GetCurSel()+1;i++)  //(int)vData.parray->cbElements

                     {

                        CString cData;

                        cData.Format("%04.2f ",fData[i]);

                        strData+= cData;

                     }

                     SafeArrayUnAccessData(vData.parray);

              }

              else

              {

                     long *lngData;

                     SafeArrayAccessData(vData.parray, (void**)&lngData );

                     for(int i=0;i<m_DataNum.GetCurSel()+1;i++)  //(int)vData.parray->cbElements

                     {

                        CString cData;

            &

nbsp;           cData.Format("%ld ",lngData[i]);

                        strData+= cData;

                     }

                     SafeArrayUnAccessData(vData.parray);

              }

 

              m_Data.SetWindowText(strData);

       }

       else

       {

        m_Data.SetWindowText(_T("ERROR"));

       }

       SafeArrayUnAccessData(vData.parray);

       SafeArrayDestroy(vData.parray);

    VariantClear(&vData);

}

 

//寫數據

void CPPI_TestDlg::OnWrite()

{

       long lngFixAddr=0,lngDataAddr=0;

       char strAddr[255];

       m_FixAddr.GetWindowText(strAddr,255);

       sscanf(strAddr,"%ld",&lngFixAddr);

      

       m_DataAddr.GetWindowText(strAddr,255);

       sscanf(strAddr,"%ld",&lngDataAddr);

 

    long DataType;

       switch (m_DataType.GetCurSel())

       {

       case 0:

              DataType=0x81;

              break;

       case 1:

              DataType=0x82;

              break;

       case 2:

              DataType=0x83;

              break;

       case 3:

              DataType=0x84;

              break;

       case 4:

              DataType=0x4;

              break;

       case 5:

              DataType=0x5;

              break;

       }

       long lngRet;

    VARIANT vData;

       VariantInit (&vData);

       if(m_DataMode.GetCurSel()==3)  //浮點數

       {

           vData.vt = VT_R4 | VT_ARRAY;

           vData.parray=SafeArrayCreateVector(VT_R4, 0, 255 );

             

              float *fDatas,fData;

              SafeArrayAccessData(vData.parray, (void**)&fDatas );

           &nbsp;  m_Data.GetWindowText(strAddr,255);

              sscanf(strAddr,"%f",&fData);

              fDatas[0]=fData;

              SafeArrayUnAccessData(vData.parray);

       }

       else

       {

           vData.vt = VT_I4 | VT_ARRAY;

           vData.parray=SafeArrayCreateVector(VT_I4, 0, 255 );     //SAFEARRAY vd;

             

              long *lngDatas,lngData;

              SafeArrayAccessData(vData.parray, (void**)&lngDatas );

              m_Data.GetWindowText(strAddr,255);

              sscanf(strAddr,"%ld",&lngData);

              lngDatas[0]=lngData;

              SafeArrayUnAccessData(vData.parray);

       }

 

    lngRet=m_PPI.WriteData(lngDataAddr,(const VARIANT &)vData,1,m_DataMode.GetCurSel(),DataType,lngFixAddr);

       if(lngRet!=0)

       {

              m_Data.SetWindowText(_T("ERROR"));

       }

       SafeArrayUnAccessData(vData.parray);

       SafeArrayDestroy(vData.parray);

    VariantClear(&vData);

}

 

詳細的示例請在下面的鏈接下載:

http://www.sky-walker.com.cn/yefan/PPIV2.rar

 

早期版本的控件下載鏈接:

http://www.sky-walker.com.cn/yefan/S7_PPI.rar

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved