在C#中调用C dll函数,结构和回调

时间:2009-11-02 06:27:24

标签: c# struct callback marshalling invoke

以下是标题文件。任何人都请在下面调用回调函数。

//Function Prototype

int PASCAL EXPORT RegisterCallbackFunctions (TCallbacks CallbackFuncs);

//Data Structure

struct TCallbacks
{
LPONUSSDREQUEST m_pOnRequest;
LPONUSSDRESPONSE m_pOnResponse;
};

struct TData
{
   DWORD  m_dwCmd;     
   BYTE   m_bVersion; 
   BYTE   m_bCodeScheme;   
   DWORD  m_dwErrorCode; 
   char   m_szMsIsdn[15];
}


//Prototypes



typedef int (*LPONUSSDREQUEST) (HANDLE hLoginInstance, HANDLE hDialog, TData data, DWORD *pdwAppParam);

typedef int (*LPONUSSDRESPONSE) (HANDLE hLoginInstance, HANDLE hDialog, char szString [ ], DWORD dwAppParam);

我已经有了hloginInstance和hDialog函数,但我需要帮助调用回调函数。

的问候, Jeanix

2 个答案:

答案 0 :(得分:0)

在.NET中,您可以使用委托:

class Program
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate int RequestDelegate(
        IntPtr hLoginInstance, 
        IntPtr hDialog, 
        IntPtr data, 
        int pdwAppParam);

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate int ResponseDelegate(
        IntPtr hLoginInstance, 
        IntPtr hDialog, 
        string szString, 
        int dwAppParam);

    [DllImport("somelib.dll")]
    public static extern void RegisterCallbackFunctions(TCallbacks callbacks);

    public struct TCallbacks
    {
        public RequestDelegate m_pOnRequest;
        public ResponseDelegate m_pOnResponse;
    }

    static void Main(string[] args)
    {
        TCallbacks callbacks;
        callbacks.m_pOnRequest = 
            (hLoginInstance, hDialog, data, pdwAppParam) => 10;
        callbacks.m_pOnResponse = 
            (hLoginInstance, hDialog, szString, dwAppParam) => 20;
        RegisterCallbackFunctions(callbacks);
    }
} 

答案 1 :(得分:0)

代码对我不起作用,我认为初始化存在问题。

错误在于此行: -  callbacks.m_pOnRequest =(hLoginInstance,hDialog,data,pdwAppParam)=> 10;

thankx, jeanix