Reputation: 53
I have a c# code which captures a fingerprint from a device. The code for capturing is written in c++ dll which returns the image through callback side by side to give live view. But the problem is that the application stops working after some time during capture. This happens because of callback method only. If I comment the code in callback method it works fine. I want to know if the callback method can be put in another thread so that the coming images do not get crashed in callback method. Following is the way how I have called the method.
/* c# code: */
[DllImport("abc.dll", EntryPoint = "capture", CharSet = CharSet.Auto, ExactSpelling = false, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I4)]
static extern int capture(callback liveImageCallback);
private delegate void callback(IntPtr img);
void capture()
{
int ret= capture(callBackLiveImage);
}
public void callBackLiveImage(IntPtr imgPointer)
{
byte[] rawData = new byte[102400];
Marshal.Copy(imgPointer, rawData, 0, 102400);
}
/* c++ code: */
typedef void (__stdcall * Callback)(unsigned char* img);
Callback LiveImageHandler;
void capture(liveCallback)
{
LiveImageHandler = liveCallback;
someMethod();
}
someMethod()
{
LiveImageHandler(raw_img);
}
Upvotes: 0
Views: 135
Reputation: 63732
You have no error handling in the callBackLiveImage
method. You're always copying 102400
. My unmanaged sense is seeing an unhandled exception like AccessViolationException
or such.
Try using a try
-catch
statement to catch the exception, and log it:
public void callBackLiveImage(IntPtr imgPointer)
{
try
{
byte[] rawData = new byte[102400];
Marshal.Copy(imgPointer, rawData, 0, 102400);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
Unhandled .NET exceptions in unmanaged code don't really sound like a good idea :)
The specific exception will give you a better idea of what you're dealing with. It might be that the imgPointer
is IntPtr.Zero
, or it might be that there's less data than you expected. Also, are you sure the C++ library is taking care of disposing of the memory?
Upvotes: 1