原理及封闭类,里面调用带有回调函数和自定义结构体的DLL的例程
分类:面向对象

使用C#拷贝String到struct

开发环境: WinXP Pro(SP2英文版) + VS.NET 2003中文版
接口库版本: CMPP2.0 API第二版(V2.6)
该例程演示了如何在C#里面调用VC6.0开发的带回调函数的API,而且回调函数的参数包含结构体,使用C#的委托和IntPtr方法实现.
由于我使用C#刚两天,这是我写的第一个C#程序,因此例程写的可能有点粗糙,但是编译和运行完全没有问题.
CMPP2.0的API封装成了标准C调用的方法,提供以下三个接口,使用的时候只要有CMPPAPI.dll就可以了.
#define DllExport extern "C" __declspec(dllexport)
DllExport int __stdcall Cmpp2Start(LPCTSTR pchSmgIp, int nMtPort, int nMoPort,
LPCTSTR pchUserName, LPCTSTR pchUserPwd, unsigned char uchVersion,
void (__stdcall *OnSmgMsg)(CMPP_SMGTOSP* css), int nConnType, void (__stdcall *OnLogFile)(LPCTSTR str));
DllExport int __stdcall Cmpp2Submit(unsigned char uchPKtotal, unsigned char uchPKnumber,
unsigned char uchNeedreport, unsigned char uchMsglevel, LPCTSTR pchServiceid,
unsigned char uchFeeusertype, LPCTSTR pchFeeterminalid, unsigned char uchTppid,
unsigned char uchTpudhi, unsigned char uchMsgfmt, LPCTSTR pchMsgsrc,
LPCTSTR pchFeetype, LPCTSTR pchFeecode, LPCTSTR pchValidtime,
LPCTSTR pchAttime, LPCTSTR pchSrcid, unsigned char uchDestusrtl,
LPCTSTR pchDestterminalid, unsigned char uchMsglen, LPCTSTR pchMsgcontent);
DllExport int __stdcall Cmpp2Release();
在C#里面如何调用API,如何声明结构体,如何使用委托实现回调函数,如何实现使用自定义结构体作为参数的回调函数,请仔细查看例程源码。注意:CMPPAPI.dll要和可执行文件放到同一个目录下,或者放到可执行文件能找到的目录,或者放到系统目录下(如:C:windowssystem32).

在网络编程中,有时候会需要重新拨号建立网络连接(如Ad点击软件通过重新拨号形成有效点击) ,下面介绍两种程序中拨号的方法.

ADSL自动拨号类,前提是在系统中已经有了一个宽带拨号连接

By dgiljr

下面是C#下面的完整的调用代码

1、最简单的方法:使用RasDial命令
    RasDial是Windows自带的命令,使用非常简单。实际使用是可将下面代码保存为一个批处理文件,然后直接运行或在程序里进行调用。

调用代码:
RASDisplay ras = new RASDisplay();
ras.Disconnect();//断线
ras.Connect("adsl");//拨号

介绍

//Class1.cs

rasdial.exe  /disconnect '断开连接
del "C:Documents and SettingshyuqinCookies*.*" /Q  '清除Cookie
rasdial.exe  连接名 连接账户 连接密码 '重新拨号
2、封装为类,灵活调用
    上面提到的方法虽然很简单,但并非标准的实现方法,使用时会受到一些限制,此时最好的办法就是将实现代码封装为类库。下面这个类库是网上一位朋友提供的,直接调用就行.
图片 1using System;
图片 2using System.Runtime.InteropServices;
图片 3
图片 4public struct RASCONN
图片 5{
图片 6    public int dwSize;
图片 7    public IntPtr hrasconn;
图片 8    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
图片 9    public string szEntryName;
图片 10    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]
图片 11    public string szDeviceType;
图片 12    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
图片 13    public string szDeviceName;
图片 14}
图片 15
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
图片 16public struct RasStats
图片 17{
图片 18    public int dwSize;
图片 19    public int dwBytesXmited;
图片 20    public int dwBytesRcved;
图片 21    public int dwFramesXmited;
图片 22    public int dwFramesRcved;
图片 23    public int dwCrcErr;
图片 24    public int dwTimeoutErr;
图片 25    public int dwAlignmentErr;
图片 26    public int dwHardwareOverrunErr;
图片 27    public int dwFramingErr;
图片 28    public int dwBufferOverrunErr;
图片 29    public int dwCompressionRatioIn;
图片 30    public int dwCompressionRatioOut;
图片 31    public int dwBps;
图片 32    public int dwConnectionDuration;
图片 33}
图片 34
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
图片 35public struct RasEntryName
图片 36{
图片 37    public int dwSize;
图片 38    //[MarshalAs(UnmanagedType.ByValTStr,SizeConst=(int)RasFieldSizeConstants.RAS_MaxEntryName

using System;
using System.Runtime.InteropServices;
public struct RASCONN
{
public int dwSize;
public IntPtr hrasconn;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=257)]
public string szEntryName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=17)]
public string szDeviceType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=129)]
public string szDeviceName;
}

本文介绍使用C#拷贝String到struct 。

using System;
// 该名称空间包含了在Visual C#中调用API的一些必要集合
using System.Runtime.InteropServices;
// 使用Sleep方法需要的命名空间
using System.Threading;

  • 1)]
    图片 39    public string szEntryName;
    图片 40    //#if WINVER5
    图片 41    //  public int dwFlags;
    图片 42    //  [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260+1)]
    图片 43    //  public string szPhonebookPath;
    图片 44    //#endif
    图片 45}
    图片 46public class RAS
    图片 47{
    图片 48    [DllImport("Rasapi32.dll", EntryPoint = "RasEnumConnectionsA",
    图片 49         SetLastError = true)]
    图片 50
        internal static extern int RasEnumConnections
    图片 51        (
    图片 52        ref RASCONN lprasconn, // buffer to receive connections data
    图片 53        ref int lpcb, // size in bytes of buffer
    图片 54        ref int lpcConnections // number of connections written to buffer
    图片 55        );
    图片 56

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
public struct RasStats
{
public int dwSize;
public int dwBytesXmited;
public int dwBytesRcved;
public int dwFramesXmited;
public int dwFramesRcved;
public int dwCrcErr;
public int dwTimeoutErr;
public int dwAlignmentErr;
public int dwHardwareOverrunErr;
public int dwFramingErr;
public int dwBufferOverrunErr;
public int dwCompressionRatioIn;
public int dwCompressionRatioOut;
public int dwBps;
public int dwConnectionDuration;
}

代码

namespace CMPPAPI_Sample_CSharp
{
//---------------------------------------------------------------------
//---------以下是DLL中需要使用的结构体的定义---------------------------
//--------Pack = 1表示结构体按一个字节对齐----------------------------
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_HEAD
{
public uint nTotalLength;
public uint nCommandId;
public uint nSeqId;
}

图片 57    [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
图片 58    internal static extern uint RasGetConnectionStatistics(
图片 59        IntPtr hRasConn,       // handle to the connection
图片 60        [In, Out]RasStats lpStatistics  // buffer to receive statistics
图片 61        );
图片 62    [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
图片 63    public extern static uint RasHangUp(
图片 64        IntPtr hrasconn  // handle to the RAS connection to hang up
图片 65        );
图片 66
    [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
图片 67    public extern static uint RasEnumEntries(
图片 68        string reserved,              // reserved, must be NULL
图片 69        string lpszPhonebook,         // pointer to full path and
图片 70        //  file name of phone-book file
图片 71        [In, Out]RasEntryName[] lprasentryname, // buffer to receive
图片 72        //  phone-book entries
图片 73        ref int lpcb,                  // size in bytes of buffer
图片 74        out int lpcEntries             // number of entries written
图片 75        //  to buffer
图片 76        );
图片 77
    [DllImport("wininet.dll", CharSet = CharSet.Auto)]
图片 78    public extern static int InternetDial(
图片 79        IntPtr hwnd,
图片 80        [In]string lpszConnectoid,
图片 81        uint dwFlags,
图片 82        ref int lpdwConnection,
图片 83        uint dwReserved
图片 84        );
图片 85
    public RAS()
图片 86    {
图片 87    }
图片 88}
图片 89public enum DEL_CACHE_TYPE //要删除的类型。
图片 90{
图片 91    File,//表示internet临时文件
图片 92    Cookie //表示Cookie
图片 93}
图片 94
public class RASDisplay
图片 95{
图片 96    [DllImport("wininet.dll", CharSet = CharSet.Auto)]
图片 97    public static extern bool DeleteUrlCacheEntry(
图片 98        DEL_CACHE_TYPE type
图片 99        );
图片 100    ******* string m_duration;
图片 101    ******* string m_ConnectionName;
图片 102    ******* string[] m_ConnectionNames;
图片 103    ******* double m_TX;
图片 104    ******* double m_RX;
图片 105    ******* bool m_connected;
图片 106    ******* IntPtr m_ConnectedRasHandle;
图片 107
    RasStats status = new RasStats();
图片 108    public RASDisplay()
图片 109    {
图片 110        m_connected = true;
图片 111
        RAS lpras = new RAS();
图片 112        RASCONN lprasConn = new RASCONN();
图片 113
        lprasConn.dwSize = Marshal.SizeOf(typeof(RASCONN));
图片 114        lprasConn.hrasconn = IntPtr.Zero;
图片 115
        int lpcb = 0;
图片 116        int lpcConnections = 0;
图片 117        int nRet = 0;
图片 118        lpcb = Marshal.SizeOf(typeof(RASCONN));
图片 119
        nRet = RAS.RasEnumConnections(ref lprasConn, ref lpcb, ref
图片 120            lpcConnections);
图片 121
        if (nRet != 0)
图片 122        {
图片 123            m_connected = false;
图片 124            return;
图片 125
        }
图片 126
        if (lpcConnections > 0)
图片 127        {
图片 128            //for (int i = 0; i < lpcConnections; i++)
图片 129
            //{
图片 130            RasStats stats = new RasStats();
图片 131
            m_ConnectedRasHandle = lprasConn.hrasconn;
图片 132            RAS.RasGetConnectionStatistics(lprasConn.hrasconn, stats);
图片 133

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
public struct RasEntryName
{
public int dwSize;
//[MarshalAs(UnmanagedType.ByValTStr,SizeConst=(int)RasFieldSizeConstants.RAS_MaxEntryName

using System;
using System.Runtime.InteropServices;
using System.Text;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_CONNECT
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string sSourceAddr;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string sAuthSource;
public byte cVersion;
public uint nTimeStamp;
}

图片 134            m_ConnectionName = lprasConn.szEntryName;
图片 135
            int Hours = 0;
图片 136            int Minutes = 0;
图片 137            int Seconds = 0;
图片 138
            Hours = ((stats.dwConnectionDuration / 1000) / 3600);
图片 139            Minutes = ((stats.dwConnectionDuration / 1000) / 60) - (Hours * 60);
图片 140            Seconds = ((stats.dwConnectionDuration / 1000)) - (Minutes * 60) - (Hours * 3600);
图片 141

  • 1)]
    public string szEntryName;
    //#if WINVER5
    //   public int dwFlags;
    //   [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260+1)]
    //   public string szPhonebookPath;
    //#endif
    }
    public class RAS

class Class1
{

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_CONNECT_RESP
{
public byte uchStatus;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string sAuthISMG;
public byte cVersion;
}

图片 142            m_duration = Hours + " hours " + Minutes + " minutes " + Seconds + " secs";
图片 143            m_TX = stats.dwBytesXmited;
图片 144            m_RX = stats.dwBytesRcved;
图片 145            //}
图片 146        }
图片 147        else
图片 148        {
图片 149            m_connected = false;
图片 150        }
图片 151

{

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct MyStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=4)] public string fname;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=4)] public string lname;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=7)] public string phone;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_SUBMIT_RESP
{
public long nMsgid;
public byte uchResult;
}

图片 152        int lpNames = 1;
图片 153        int entryNameSize = 0;
图片 154        int lpSize = 0;
图片 155        RasEntryName[] names = null;
图片 156
        entryNameSize = Marshal.SizeOf(typeof(RasEntryName));
图片 157        lpSize = lpNames * entryNameSize;
图片 158
        names = new RasEntryName[lpNames];
图片 159        names[0].dwSize = entryNameSize;
图片 160
        uint retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);
图片 161
        //if we have more than one connection, we need to do it again
图片 162        if (lpNames > 1)
图片 163        {
图片 164            names = new RasEntryName[lpNames];
图片 165            for (int i = 0; i < names.Length; i++)
图片 166            {
图片 167                names[i].dwSize = entryNameSize;
图片 168            }
图片 169
            retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);
图片 170
        }
图片 171        m_ConnectionNames = new string[names.Length];
图片 172

[DllImport("Ra<a href="" target="_blank">SAP</a>i32.dll", EntryPoint="RasEnumConnectionsA",
      SetLastError=true)]

public static void Main()
{
string buffer = "abcdefgh2223333";
IntPtr pBuf = Marshal.StringToBSTR(buffer);
MyStruct ms = (MyStruct)Marshal.PtrToStructure(pBuf,typeof(MyStruct));
Console.WriteLine("fname is: {0}",ms.fname);
Console.WriteLine("lname is: {0}",ms.lname);
Console.WriteLine("phone is: {0}",ms.phone);
}
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_STATUS_REPORT
{
public long nMsgid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 7)]
public string sStat;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sSubmitTime;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sDoneTime;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string sDestTerminalId;
public uint nSmscSeq;
}

图片 173        if (lpNames > 0)
图片 174        {
图片 175            for (int i = 0; i < names.Length; i++)
图片 176            {
图片 177                m_ConnectionNames[i] = names[i].szEntryName;
图片 178            }
图片 179        }
图片 180    }
图片 181
    public string Duration
图片 182    {
图片 183        get
图片 184        {
图片 185            return m_connected ? m_duration : "";
图片 186        }
图片 187    }
图片 188
    public string[] Connections
图片 189    {
图片 190        get
图片 191        {
图片 192            return m_ConnectionNames;
图片 193        }
图片 194    }
图片 195
    public double BytesTransmitted
图片 196    {
图片 197        get
图片 198        {
图片 199            return m_connected ? m_TX : 0;
图片 200        }
图片 201    }
图片 202    public double BytesReceived
图片 203    {
图片 204        get
图片 205        {
图片 206            return m_connected ? m_RX : 0;
图片 207
        }
图片 208    }
图片 209    public string ConnectionName
图片 210    {
图片 211        get
图片 212        {
图片 213            return m_connected ? m_ConnectionName : "";
图片 214        }
图片 215    }
图片 216    public bool IsConnected
图片 217    {
图片 218        get
图片 219        {
图片 220            return m_connected;
图片 221        }
图片 222    }
图片 223
    public int Connect(string Connection)
图片 224    {
图片 225        int temp = 0;
图片 226        uint INTERNET_AUTO_DIAL_UNATTENDED = 2;
图片 227        int retVal = RAS.InternetDial(IntPtr.Zero, Connection, INTERNET_AUTO_DIAL_UNATTENDED, ref temp, 0);
图片 228        return retVal;
图片 229    }
图片 230    public void Disconnect()
图片 231    {
图片 232        RAS.RasHangUp(m_ConnectedRasHandle);
图片 233    }
图片 234}
调用方法:

internal static extern int RasEnumConnections
       (
       ref RASCONN lprasconn, // buffer to receive connections data
       ref int lpcb, // size in bytes of buffer
       ref int lpcConnections // number of connections written to buffer
       );

From :

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_MO_MSGCONTENT
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 160)]
public string sMsgcontent;
public CMPP_STATUS_REPORT csr;
}

图片 235RASDisplay ras = new RASDisplay();
图片 236ras.Disconnect();//断开连接
图片 237ras.Connect("ADSL");//重新拨号

[DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
internal static extern uint RasGetConnectionStatistics(
       IntPtr hRasConn,    // handle to the connection
       [In,Out]RasStats lpStatistics   // buffer to receive statistics
       );
[DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
public extern static uint RasHangUp(
       IntPtr hrasconn   // handle to the RAS connection to hang up
       );

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_DELIVER
{
public long nMsgid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string sDestid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sServiceid;
public byte uchTppid;
public byte uchTpudhi;
public byte uchMsgfmt;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string sSrcterminalid;
public byte uchRegisteredDelivery;
public byte uchMsglength;

 

[DllImport("rasapi32.dll",CharSet=CharSet.Auto)]
public extern static uint RasEnumEntries (
       string reserved,              // reserved, must be NULL
       string lpszPhonebook,       // pointer to full path and
       //   file name of phone-book file
       [In,Out]RasEntryName[] lprasentryname, // buffer to receive
       //   phone-book entries
       ref int lpcb,                // size in bytes of buffer
       out int lpcEntries          // number of entries written
       //   to buffer
       );

biqiong2004@hotmail.com

public CMPP_MO_MSGCONTENT mo_msg;

[DllImport("wininet.dll",CharSet=CharSet.Auto)]
public extern static int InternetDial(
       IntPtr hwnd,
       [In]string lpszConnectoid,
       uint dwFlags,
       ref int lpdwConnection,
       uint dwReserved
       );

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string sReserved;
}

public RAS()
{

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_SUBMIT
{
public long nMsgid;
public byte uchPkTotal;
public byte uchPkNumber;
public byte uchRegisteredDelivery;
public byte uchMsgLevel;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sServiceId;
public byte uchFeeUserType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string sFeeTerminalId;
public byte uchTpPid;
public byte uchTpUdhi;
public byte uchMsgFmt;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string sMsgSrc;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
public string sFeeType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
public string sFeeCode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]
public string sValidTime;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]
public string sAtTime;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21)]
public string sSrcId;
public byte uchDstUsrTl;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 21*100)]
public string sDstTerminalId;
public byte uchMsgLength;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 160)]
public string sMsgContent;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string sReserved;
}

}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_QUERY
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string sTime;
public byte uchQueryType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sQueryCode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string sReserved;
}

  
}
public enum DEL_CACHE_TYPE //要删除的类型。
{
File,//表示internet临时文件
Cookie //表示Cookie
};
public class RASDisplay
{
[DllImport("wininet.dll",CharSet=CharSet.Auto)]
public static extern bool   DeleteUrlCacheEntry(
       DEL_CACHE_TYPE type
       );
******* string m_duration;
******* string m_ConnectionName;
******* string[] m_ConnectionNames;
******* double m_TX;
******* double m_RX;
******* bool m_connected;
******* IntPtr m_ConnectedRasHandle;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_QUERY_RESP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public string sTime;
public byte uchQueryType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string sQueryCode;
public uint nMTTLMsg; //从SP接收消息总数.
public uint nMTTLUsr; //从SP接收用户总数.
public uint nMTScs; //成功转发数量.
public uint nMTWT; //待转发数量.
public uint nMTFL; //转发失败数量.
public uint nMOScs; //向SP成功送达数量.
public uint nMOWT; //向SP待送达数量.
public uint nMOFL; //向SP送达失败数量.
}

RasStats status = new RasStats();
public RASDisplay()
{
       m_connected = true;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_CANCEL
{
public long nMsgid;
}

       RAS lpras = new RAS();
       RASCONN lprasConn = new RASCONN();

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_CANCEL_RESP
{
public byte uchSuccessId;
}

       lprasConn.dwSize = Marshal.SizeOf(typeof(RASCONN));
       lprasConn.hrasconn = IntPtr.Zero;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_ACTIVETEST_RESP
{
public byte uchReserved;
}

       int lpcb = 0;
       int lpcConnections = 0;
       int nRet = 0;
       lpcb = Marshal.SizeOf(typeof(RASCONN));

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_BODY
{
public CMPP_CONNECT_RESP pk_connectresp;
public CMPP_SUBMIT_RESP pk_submitresp;
public CMPP_QUERY_RESP pk_queryresp;
public CMPP_DELIVER pk_deliver;
public CMPP_CANCEL_RESP pk_cancelresp;
public CMPP_ACTIVETEST_RESP pk_activetestresp;
}

       nRet = RAS.RasEnumConnections(ref lprasConn, ref lpcb, ref
         lpcConnections);

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_SMGTOSP
{
public CMPP_HEAD pk_head;
public CMPP_BODY pk_body;
}
//----------------DLL需要使用的结构体的定义----------------------------
//---------------------------------------------------------------------

       if(nRet != 0)

//----------------声明两个委托,相当于VC里面的回调函数------------------
public delegate void OnSmgMsg(IntPtr css);
public delegate void OnLogMsg(string str);
//---------------------------------------------------------------------

       {
         m_connected = false;
         return;

class Class1
{
//--------------------------------------------------------------------------
//--------------DLL中的API函数声明------------------------------------------
// 1.Start Func
[DllImport("CMPPAPI.dll")]
public static extern int Cmpp2Start(string pchSmgIp, int nMtPort, int nMoPort,
string pchUserName, string pchUserPwd, byte uchVersion,
OnSmgMsg pf, int nConnType, OnLogMsg pf2);

       }

// 2.Submit Func
[DllImport("CMPPAPI.dll")]
public static extern int Cmpp2Submit(byte uchPKtotal, byte uchPKnumber,
byte uchNeedreport, byte uchMsglevel, string pchServiceid,
byte uchFeeusertype, string pchFeeterminalid, byte uchTppid,
byte uchTpudhi, byte uchMsgfmt, string pchMsgsrc,
string pchFeetype, string pchFeecode, string pchValidtime,
string pchAttime, string pchSrcid, byte uchDestusrtl,
string pchDestterminalid, byte uchMsglen, string pchMsgcontent);

       if(lpcConnections > 0)
       {

// 3.Release
[DllImport("CMPPAPI.dll")]
public static extern int Cmpp2Release();
//--------------DLL中的API函数声明------------------------------------------
//--------------------------------------------------------------------------

         //for (int i = 0; i < lpcConnections; i++)

//-------------这儿使用IntPtr实现与结构体之间的转换----------------
public static void OnMsg(IntPtr ptr)
{
CMPP_SMGTOSP css = new CMPP_SMGTOSP();
css = (CMPP_SMGTOSP)Marshal.PtrToStructure(ptr, typeof(CMPP_SMGTOSP));

         //{
         RasStats stats = new RasStats();

uint nCmdId = css.pk_head.nCommandId;
Console.WriteLine(css.pk_head.nCommandId);
if ( nCmdId == 0x80000004) {
// Submit应答消息
}
else if ( nCmdId == 0x0000005) {
// Deliver消息
}

         m_ConnectedRasHandle = lprasConn.hrasconn;
         RAS.RasGetConnectionStatistics(lprasConn.hrasconn, stats);

return;
}

         m_ConnectionName = lprasConn.szEntryName;

//------------第二个委托函数的定义-------------------------------
public static void OnLog(string str)
{
Console.WriteLine(str);
return;
}

         int Hours = 0;
         int Minutes = 0;
         int Seconds = 0;

///
/// 应用程序的主入口点。
///
[STAThread]
static void Main(string[] args)
{
Class1 c1 = new Class1();
OnSmgMsg pt = new OnSmgMsg(OnMsg);
OnLogMsg pLog = new OnLogMsg(OnLog);

         Hours = ((stats.dwConnectionDuration /1000) /3600);
         Minutes = ((stats.dwConnectionDuration /1000) /60) - (Hours * 60);
         Seconds = ((stats.dwConnectionDuration /1000)) - (Minutes * 60) - (Hours * 3600);

//-------------启动模块,连接网关,收到消息以后会触发OnSmgMsg函数------------------------------
int nRetCode = Cmpp2Start("127.0.0.1", 7890, 7891, "901234", "1234", (byte)0x20, pt, 0, pLog);
if ( 0 == nRetCode)
{
Console.WriteLine("Connect Smg successn");

         m_duration = Hours   +   " hours "   + Minutes + " minutes " + Seconds + " secs";
         m_TX = stats.dwBytesXmited;
         m_RX = stats.dwBytesRcved;

while ( true)
{
//----------向网关提交Submit消息----------
nRetCode = Cmpp2Submit(1, 1,
1, 3, "2939",
0, "", 0,
0, 0, "901234",
"02", "000020", "",
"", "01850", 1,
"8613660617374", 8, "测试消息");

         //}

if ( 0 == nRetCode)
{
Console.WriteLine("Submit Success.");
}
else {
Console.WriteLine("Submit Fail.");
}

       }
       else
       {
         m_connected = false;
       }

// Sleep5秒钟
Thread.Sleep(5000);
}

       int lpNames = 1;
       int entryNameSize = 0;
       int lpSize = 0;
       RasEntryName[] names = null;

//-----释放连接-----
Cmpp2Release();
}
else {
Console.WriteLine("Connect SMG Fail With Error: " + nRetCode);
}
}
}
}

       entryNameSize=Marshal.SizeOf(typeof(RasEntryName));
       lpSize=lpNames*entryNameSize;

       names=new RasEntryName[lpNames];
       names[0].dwSize=entryNameSize;

       uint retval = RAS.RasEnumEntries(null,null,names,ref lpSize,out lpNames);

       //if we have more than one connection, we need to do it again
       if(lpNames > 1)
       {
         names=new RasEntryName[lpNames];
         for(int i=0;i<names.Length;i++)
         {
            names[i].dwSize=entryNameSize;
         }

         retval = RAS.RasEnumEntries(null,null,names,ref lpSize,out lpNames);

       }
       m_ConnectionNames = new string[names.Length];

       if(lpNames>0)
       {
         for(int i=0;i<names.Length;i++)
         {

            m_ConnectionNames[i] = names[i].szEntryName;

         }
       }
}

public string Duration
{
       get
       {
         return m_connected ? m_duration : "";
       }
}

public string[] Connections
{
       get
       {
         return m_ConnectionNames;
       }
}

public double BytesTransmitted
{
       get
       {
         return m_connected ? m_TX : 0;
       }
}
public double BytesReceived
{
       get
       {
         return m_connected ? m_RX :   0;

       }
}
public string ConnectionName
{
       get
       {
         return m_connected ? m_ConnectionName : "";
       }
}
public bool IsConnected
{
       get
       {
         return m_connected;
       }
}

public int Connect(string Connection)
{
       int temp = 0;
       uint INTERNET_AUTO_DIAL_UNATTENDED = 2;
       int retVal = RAS.InternetDial(IntPtr.Zero,Connection,INTERNET_AUTO_DIAL_UNATTENDED,ref temp,0);
       return retVal;
}
public void Disconnect()
{
       RAS.RasHangUp(m_ConnectedRasHandle);
}
}

本文由10bet手机官网发布于面向对象,转载请注明出处:原理及封闭类,里面调用带有回调函数和自定义结构体的DLL的例程

上一篇:中如何对当前窗体进行打印预览 下一篇:没有了
猜你喜欢
热门排行
精彩图文