Sign in to follow this  
Promit

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

Recommended Posts

Promit    13246
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.

Share this post


Link to post
Share on other sites
paulecoyote    1065
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]

Share this post


Link to post
Share on other sites
TheBluMage    372
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!

Share this post


Link to post
Share on other sites
Washu    7829
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.";
}
}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this