Solved

problem with callback function using unmanaged dll

Posted on 2004-08-04
16
511 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
16 Comments
 
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

687 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