Solved

problem with callback function using unmanaged dll

Posted on 2004-08-04
16
507 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
.NET 2008 VB and C# 6 48
defining NULL or 0 10 50
bound data table problem 2 40
Unlocking a column in excel using C# 17 27
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

749 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