Hi all,
I have a 3rd party DLL (non-COM) that I am accessing from managed code via PInvoke. The third party function, reads a file, crunches data, and generates a results file. I have wrapped the dll's functions with static function calls from a managed .NET singleton dll. This routine works fine as long as I am running in the foreground thread. As soon as I call this function from a background thread, however it crashes with the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
I have checked the marshalling with CLRSpy and everything looks to be in order. Before I post any code, I was wondering what general issues could be causing this problem to show up in background worker threads only. I get a results file created but it has 0 bytes. Any suggestions for further debugging efforts would be appreciated as well.
Regards,
Zam

Interop problem - unmanaged code fails only while in background thread
Jeff Miller
I have a 3rd party DLL (non-COM) that I am accessing from managed code via PInvoke. The third party function, reads a file, crunches data, and generates a results file. I have wrapped the dll's functions with static function calls from a managed .NET singleton dll. This routine works fine as long as I am running in the foreground thread. As soon as I call this function from a background thread, however it crashes with the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
This routine does not do any UI and is set up by feeding it an input filename via a previous call. I have checked the marshalling with CLRSpy and everything looks to be in order. Before I post any code, I was wondering what general issues could be causing this problem to show up in background worker threads only. I get a results file created but it has 0 bytes.
Any suggestions for further debugging efforts would be appreciated as well.
Regards,
Zam
nicbkw
I don't know of any general issues with background thread versus foreground threads that result in NullReferenceException.
One possibility [probable, even] is that the 3rd party dll is crashing(AV) when called from the background thread.
You can find a bit more info on the Exception mapping (e.g. AV->NullReferenceException) on Christopher Brumme's excellent CLR architecture blog - specifically Exceptions (Chris is one of the CLR architects).
Have you tried running the code (especially the 3rd party DLL) under a native debugger (such as WinDBG) - breaking on first chance exceptions
Thanks!
Stephen
http://blogs.msdn.com/stfisher
LapDragon
You can name other cases but check first abovementioned.