Solved

problem with callback function using unmanaged dll

Posted on 2004-08-04
16
503 Views
Last Modified: 2010-04-15
Hi all,

I have a C++ dll i will be using in C#.  Proceeded with using dllImport to access the dll's functions.
DLL has function Write() and SetCallback(BOOL (*pCallBack)(WORD, DWORD, char*))
SetCallback() function is called when Write() is currently writing to be able to show progress.

I do this:

//initializations
SetCallback(CallBackFunction);
try
{
   Write();
}
catch(Exception err)
{
   //handle err
}

This code catches NullReferenceException. :(
When i comment out SetCallBack() function, everything works fine.

Anyone have any ideas as to the cause?


Thanks
0
Comment
Question by:3Mann
  • 8
  • 4
16 Comments
 
LVL 9

Expert Comment

by:s_sansanwal
ID: 11722834
0
 
LVL 1

Author Comment

by:3Mann
ID: 11723395
hi, as i see it, i think i already implemented my callback function as to what was stated in the link...
i cant seem to find the cause of the problem...
anyone have any ideas?
0
 
LVL 1

Author Comment

by:3Mann
ID: 11723399
must the callback function be static? :-/
0
 
LVL 7

Expert Comment

by:Ceiled
ID: 11723809
No, the callback function definitely doesn't need to be static...out of curiousity, do you hold onto any references to CallBackFunction? The code you posted doesn't really say what type CallBackFunction is or how you created it, so I'm assuming it's a shortcut for "new SomeDelegateType(CallBackFunction)" or something similar -- please correct me if I'm wrong.

I've seen problems in the past where delegates are marshalled to unmanaged code and no managed references are maintained and then GC collects the delegate, and after that, invocations throw NullRefException. It looks like you're calling SetCallback() and then Write() in the same function, so try just caching CallBackFunction in a local variable and see if that helps. In fact, just to be completely safe, why not go the next step and pin the delegate? Here's the modified version of your code...

using System.Runtime.InteropServices;
// ...

//initializations
GCHandle callbackHandle = GCHandle.Allocate(CallBackFunction, GCHandleType.Pinned);
SetCallback((CallBackFunctionDelegate)callbackHandle.Target);
try
{
   Write();
}
catch(Exception err)
{
   //handle err
}
finally
{
   callbackHandle.Free(); // Make sure to free the handle in the finally block, or you may end up with uncollectable memory for the life of the AppDomain
}

If you're already holding onto a reference, try adding the pinning part...if none of that helps, you might try providing more details (such as how you're obtaining CallBackFunction and what type it is, etc).
0
 
LVL 1

Author Comment

by:3Mann
ID: 11724028
i did below code but exception at GCHandle initialization.  What did i do wrong?
exception is: "Object contains non-primitive or non-blittable data."
BTW, my delegate has a marshalled parameter.

//initializations
CallBackFunctionDelegate objCallback = new CallBackFunctionDelegate(CallBackFunction);
GCHandle callbackHandle = GCHandle.Alloc(objCallback, GCHandleType.Pinned);   //exception here
SetCallback((CallBackFunctionDelegate)callbackHandle.Target);
try
{
   Write();
}
catch(Exception err)
{
   //handle err
}
finally
{
   callbackHandle.Free(); // Make sure to free the handle in the finally block, or you may end up with uncollectable memory for the life of the AppDomain
}
0
 
LVL 7

Expert Comment

by:Ceiled
ID: 11727662
Hmmm...that's an interesting error. Can you post the signature of your delegate?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:3Mann
ID: 11731992
here's the signature of my delegate...

public delegate bool WriteProgressDelegate(int intCmd, uint intParam, uint intUser, [MarshalAs(UnmanagedType.LPArray)]byte[] byData);

callback function signature in dll is below:
BOOL (*pCall)(WORD wCmd,DWORD dwParam,DWORD dwUser,char *)

did i do my C# right?
0
 
LVL 1

Author Comment

by:3Mann
ID: 11731996
i also tried using this but still same error:

public unsafe delegate bool WriteProgressDelegate(int intCmd, uint intParam, uint intUser, byte *pbyData);
0
 
LVL 1

Author Comment

by:3Mann
ID: 11732067
BTW, the SetCallback function has parameters as below:

BOOL SetCallback(HANDLE hRec,BOOL (*pCall)(WORD wCmd,DWORD dwParam),DWORD dwUser)

and i invoke in C# like below:
[DllImport("external.dll")]
private static extern bool SetCallback(IntPtr hRec, BHAProgressDelegate callback, uint intUser);


in C++, the hWnd of current window is passed to paramater dwUser.  in my C# prog, i pass 0 as intUser.
Does this parameter have an effect on the callback function?
0
 
LVL 7

Expert Comment

by:Ceiled
ID: 11732276
Wait...are you sure you have the SetCallback() signature right? Because the signature of the function pointer it's taking doesn't match the signature of the delegate you've defined, or the signature you described two posts above, or the signature you gave when you first posted this problem. You've now posted a total of three different signatures for that callback function...what is the right signature? Having the wrong signature shouldn't cause the pinining to fail, but it *might*, potentially, cause the original problem.
0
 
LVL 1

Author Comment

by:3Mann
ID: 11732429
ceiled, thanx for the reply.  i was thinking i got it right :) now im not very sure...
anyway, in my previous posts, there are only 2 functions... 1 for setting the callback, nd the other a pointer to the call back function.  pls refer below:

signatures from C++ dll:
BOOL SetCallback(HANDLE hRec,BOOL (*pCall)(WORD wCmd,DWORD dwParam),DWORD dwUser); //this fcn sets the pointer to the callbackfunction
BOOL (*pCall)(WORD wCmd,DWORD dwParam,DWORD dwUser,char *);  //this is the signature for the callback function

what i did in C#:
//declarations
[DllImport("external.dll")]
private static extern bool SetCallback(IntPtr hRec, BHAProgressDelegate callback, uint intUser);
public delegate bool WriteProgressDelegate(int intCmd, uint intParam, uint intUser, [MarshalAs(UnmanagedType.LPArray)]byte[] byData);

//using in code
WriteProgressDelegate Callbackfcn = new WriteProgressDelegate(this.myCallback);  //declare callback function instance
private bool myCallback(int intCmd, uint intParam, uint intUser, [MarshalAs(UnmanagedType.LPArray)]byte[] byData){ /*handlers here*/ }
SetCallback(m_hnd, Callbackfcn, 0);  //set callback function to local callback handler

pls enlighten me, what did i do wrong?
0
 
LVL 1

Author Comment

by:3Mann
ID: 11732897
oh... i just saw what you mean about diff signatures.... this is a typo...

BOOL SetCallback(HANDLE hRec,BOOL (*pCall)(WORD wCmd,DWORD dwParam),DWORD dwUser);
is supposed to be

BOOL SetCallback(HANDLE hRec,BOOL (*pCall)(WORD wCmd,DWORD dwParam,DWORD dwUser,char *),DWORD dwUser);

0
 
LVL 7

Accepted Solution

by:
Ceiled earned 500 total points
ID: 11733436
The only thing I see that might be a problem is that a WORD is actually an unsigned short. Try changing the first parameter in your delegate to a ushort and see if that helps...I don't think that would give the error you're seeing, but it's worth a shot. You might also try putting [MarshalAs(UnmanagedType.FunctionPtr)] on the delegate parameter, just in case.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why, and when, to use Windows Workflow 1 32
LINQ - C# to VB convertion 12 46
Stream.BeginRead and Stream.EndRead in .NET Core 5 37
C# Json POSt to Rest API 4 36
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now