在C#裡面調用帶有回呼函數和自訂結構體的DLL的常式

來源:互聯網
上載者:User
函數 開發環境: 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:\windows\system32).


下面是C#下面的完整的調用代碼

//Class1.cs

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

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;
}

[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;
}

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

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

[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;
}

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

[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;

public CMPP_MO_MSGCONTENT mo_msg;

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

[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;
}

[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送達失敗數量.
}

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

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

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

[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;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CMPP_SMGTOSP
{
public CMPP_HEAD pk_head;
public CMPP_BODY pk_body;
}
//----------------DLL需要使用的結構體的定義----------------------------
//---------------------------------------------------------------------


//----------------聲明兩個委託,相當於VC裡面的回呼函數------------------
public delegate void OnSmgMsg(IntPtr css);
public delegate void OnLogMsg(string str);
//---------------------------------------------------------------------

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);

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

//-------------這兒使用IntPtr實現與結構體之間的轉換----------------
public static void OnMsg(IntPtr ptr)
{
CMPP_SMGTOSP css = new CMPP_SMGTOSP();
css = (CMPP_SMGTOSP)Marshal.PtrToStructure(ptr, typeof(CMPP_SMGTOSP));

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

return;
}

//------------第二個委託函數的定義-------------------------------
public static void OnLog(string str)
{
Console.WriteLine(str);
return;
}

///
/// 應用程式的主進入點。
///
[STAThread]
static void Main(string[] args)
{
Class1 c1 = new Class1();
OnSmgMsg pt = new OnSmgMsg(OnMsg);
OnLogMsg pLog = new OnLogMsg(OnLog);

//-------------啟動模組,串連網關,收到訊息以後會觸發OnSmgMsg函數------------------------------
int nRetCode = Cmpp2Start("127.0.0.1", 7890, 7891, "901234", "1234", (byte)0x20, pt, 0, pLog);
if ( 0 == nRetCode)
{
Console.WriteLine("Connect Smg success\n");

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.");
}

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

//-----釋放串連-----
Cmpp2Release();
}
else {
Console.WriteLine("Connect SMG Fail With Error: " + nRetCode);
}
}
}
}



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.