Open rainit2006 opened 6 years ago
给C++程序提供一个wrapper(C++), 用来调用客户端的dll API。
wrapper程序提供了接口: Iniitialize, Finalize, 各个API的接口
Initialize函数的实现核心: 1, hModule=::LoadLibraryW(dll文件的路径) 2,获得dll里各个API的指针: pAPIxxxx = (pAPIxxxx):: GetProcAddress(hModule, "APIxxxx");
Finalize 给dll的API的指针设为NULL,然后调用::FreeLibrary()
各个API函数 把函数的参数传给相应的API指针里。
同理,给C#程序提供的wrapper(C#)也提供了同样的接口。 只是C#程序加载C++ 的dll时比较麻烦(两者变量不统一),还要用到Marshal.GetDelegateForFunctionPointer函数来获得dll里的API指针,所以先定一个DLLInvoke类,封装了一些常见的处理,包括LoadLibrary和Marshal.GetDelegateForFunctionPointer调用。 然后在Wrapper里利用DLLInvoke类实现对dll API的delegate.
///在初始化时取得每个函数的delegate函数 public static int Initialize(string strAppID) { ... [UnmangedFunctionPointer(CallingConvention.Cdecl)] private delegate int APIxxxxDelegate(IntPtr pstrApplicationID, int iKeynum, ..... ) private static APIxxxxDelegate s_APIxxxxDelegate; s_APIxxxxDelegate = (APIxxxxDelegate)dllInvoke.invoke("APIxxxxx", typeof(APIxxxxDelegate)); ... } //在每个函数公开接口里,调用对应的delegate函数来处理参数。 public static int APIxxxx(string pstrApplicationID, int iKeyNum, ....) { result = s_APIxxxxxDelegate(StringToIntPtr(pstrApplicationID), ....); }
给C++程序提供一个wrapper(C++), 用来调用客户端的dll API。
wrapper程序提供了接口: Iniitialize, Finalize, 各个API的接口
Initialize函数的实现核心: 1, hModule=::LoadLibraryW(dll文件的路径) 2,获得dll里各个API的指针: pAPIxxxx = (pAPIxxxx):: GetProcAddress(hModule, "APIxxxx");
Finalize 给dll的API的指针设为NULL,然后调用::FreeLibrary()
各个API函数 把函数的参数传给相应的API指针里。
同理,给C#程序提供的wrapper(C#)也提供了同样的接口。 只是C#程序加载C++ 的dll时比较麻烦(两者变量不统一),还要用到Marshal.GetDelegateForFunctionPointer函数来获得dll里的API指针,所以先定一个DLLInvoke类,封装了一些常见的处理,包括LoadLibrary和Marshal.GetDelegateForFunctionPointer调用。 然后在Wrapper里利用DLLInvoke类实现对dll API的delegate.