[.net] What can cause a NullReferenceException on a call to a native DLL?

Started by
2 comments, last by Washu 19 years, 8 months ago
I've got a strange problem where I'm getting NullReferenceExceptions on calls into a native DLL. It's doubly strange because the function is a Shared member of a class (C# static) and there aren't any reference types actually being used. Any ideas?

'earlier
		<DllImport("R3D091_Core.DLL")> Private Shared Function CHLP_R3DColor (ByVal r As Short, ByVal g As Short, ByVal b As Short, ByVal a As Short) As R3DColor
			End Function

'later
		Public Shared Function R3DColor_Fill(ByVal r As Short, ByVal g As Short, ByVal b As Short, ByVal a As Short) As R3DColor
			Return CHLP_R3DColor(r, g, b, a)
		End Function


The exception happens on that Return statement. R3DColor is a Structure, so it's a value type rather than a reference type. I'm thoroughly confused.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Advertisement
Is it possible that CHLP_R3DColor is returning a non-initalised value type?

eg (c#)

int i; //Never assigned a value
return i;

EDIT: Changed "If" to "Is"

[Edited by - paulecoyote on August 3, 2004 4:46:30 PM]
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.
I've written a few graphics effects in C++ and put them in native DLLs. On several occasions, I found that if the DLL function tried to access memory that wasn't yet allocated (usually overstepping array bounds) the calling .NET app would throw a NullReferenceException. I have no idea why (it doesn't seem like the .NET app should have much say in what native functions do with memory) or if it has anything to do with your problem, but I just thought I'd mention it. Good luck!
The .net framework wraps all native code calls in a safe wrapper. This wrapper provides protection against things like accessing a null or bad pointer. You can actually provide your own protection for these cases using SEH handlers (which is what .net wraps your unmanaged code in.)

Just as a simple example:

#include <iostream>#include <windows.h>int filter (int code) {	if(code == EXCEPTION_ACCESS_VIOLATION)		return EXCEPTION_EXECUTE_HANDLER;	return EXCEPTION_CONTINUE_SEARCH;}int main() {	__try {		int* a;		*a = 0;	}	__except(filter(GetExceptionCode())) {		std::cout<<"Bad pointer accessed.";	}}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

This topic is closed to new replies.

Advertisement