Odd unmanaged calling managed code issues

  • Thread starter Thread starter Bill Soudan
  • Start date Start date
B

Bill Soudan

Hi all,

I'm a MS/.NET newbie, diving right into CLR interop. I've worked
through the various issues foreign to me as a UNIX guy: multiple heap
issues because I was linking to different CRT instances (ugh), calling
conventions, marshalling, etc. I'm stumped on one issue, though.

Quick structural overview: straight C dll wrapped by C# wrapper class.
C# wrapper provides the implementation for a number of function
callbacks via delegates that the C dll invokes. C# wrapper object is
in turn instantiated by a per-request handler thread. C dll is thread
safe.

The stumper: the first time I create the wrapper thread and try to
call the C dll, an exception is thrown when the C dll tries to call
the C# wrapper via a function pointer. The odd part is it's only the
first time -- the second and succeeding calls work just fine. I've
verified there is a function pointer by printing out the value.

C definition: char *(__stdcall *func)(void *, char *);
C# delegate: unsafe delegate string func(void *, sbyte *);

Via instrumenting the code, I'm certain the exception is being thrown
after the C code invokes the function call via the pointer, but before
control reaches my C# delegate. Usually I get:

Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object.

but sometimes I get:

Unhandled Exception: System.Runtime.InteropServices.SEHException:
External component has thrown an exception.

Any ideas would be appreciated.

Thanks,
Bill
 
(e-mail address removed) (Bill Soudan) wrote in message
Via instrumenting the code, I'm certain the exception is being thrown
after the C code invokes the function call via the pointer, but before
control reaches my C# delegate. Usually I get:

Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object.

but sometimes I get:

Unhandled Exception: System.Runtime.InteropServices.SEHException:
External component has thrown an exception.

After much searching, turns out I wasn't saving references to my
delegates, so they were being deleted by the garbage collector while
still in use.

Bill
 
Back
Top