Solved

problem with callback function using unmanaged dll

Posted on 2004-08-04
16
502 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

705 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

18 Experts available now in Live!

Get 1:1 Help Now