2

I need to call a function from unmanaged dll (C++) from my C# code. The function raise a callback function and I have to implement the function in my project.

The C++ code is:

/**
Definition: callback funcion of ReceiveStream
Input:
hHandle:    return value of LoadFile function
stream:   real infrared data stream 
len:            stream len
nTime:      stream time
Return:  =0 success < 0 fail
*/
typedef int (WINAPI *FILESTREAMCALLBACK)(HANDLE hHandle, void *stream, int len, int nTime);

//  extern STREAMCALLBACK m_GetStream;

/**
Definition: to get real-time data stream
Input:
hHandle:        return value of LoadFile function
GetStream:   call back function
Return:  =0 success < 0 fail
*/
int IFR_API ReceiveStream(HANDLE hHandle, FILESTREAMCALLBACK GetStream);

and my C# code is:

public delegate int FILESTREAMCALLBACK(IntPtr hHandle, IntPtr stream, int len, int nTime);

[SecurityPermission(SecurityAction.Assert, Unrestricted = true)]
    [DllImport("Test.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    public static extern int ReceiveStream(IntPtr hHandle, FILESTREAMCALLBACK GetStream);

private void button1_Click(object sender, EventArgs e)
    {
int iFileStream = ReceiveStream(new IntPtr(iResult), TestFunc);
}

static int TestFunc(IntPtr hHandle, IntPtr stream, int len, int nTime)
    {
        MessageBox.Show("hello");
        return 1;
    }

Bu the TestFunc wont fire. How can I fix it? I would be happy if you let me know the right answer for that.

  • The code is wrong, it will crash when the garbage collector collects the delegate object. You must store it in a static variable so that can't happen. But that's not your problem, yet, your program didn't crash. You need to debug the native code to find out why it doesn't make the callback. – Hans Passant Dec 23 '14 at 15:57
  • @HansPassant Is it really wrong in case of synchronous call? [This](http://stackoverflow.com/a/5470522/4074081) answer and linked article states opposite. UPD - Eric Lippert [states](http://stackoverflow.com/a/5465380/4074081) that it is really wrong approach. – dewaffled Dec 23 '14 at 16:06
  • No, then it is not wrong. But still the same problem, you need to debug the native code. – Hans Passant Dec 23 '14 at 19:15
  • Actually, I cant't debug the native code, because it's a SDK and I haven't any source code of that. However, It is working in another C++ project now, But has problem in my C# project. – sasan abbasi Dec 24 '14 at 07:03

0 Answers0