-1

I have encountered a NullReferenceException in an odd location. You can see where it is in the picture:

Picture

The exception was thrown outside of try catch and after return. And both Move and MoveResult data types are structures and are not reference type.

Here are the details of the exception:

System.NullReferenceException was unhandled
      Message=Object reference not set to an instance of an object.
      Source=MatinChess.Net
      StackTrace:
           at MatinChess.Net.MatinChess.MovePiece(Move move) in C:\Users\Matin\Documents\GitHub\MatinChessDLL\dotnet\MatinChess.Net\MatinChess.cs:line 37
           at MatinChess.Net.Demo.Program.Main(String[] args) in C:\Users\Matin\Documents\GitHub\MatinChessDLL\dotnet\MatinChess.Net.Demo\Program.cs:line 31
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

I am using .NET Framework 2.0 on Visual Studio 2015 community edition.

Edit

When I comment the ExternMethods.MovePiece line, it does not throw the exception.

Here is the definition of this method:

[DllImport(dll, CallingConvention = CallingConvention.Cdecl)]
public extern static void MovePiece(Move movement, ref MoveResult result);
Matin Lotfaliee
  • 1,745
  • 2
  • 21
  • 43

1 Answers1

1

You've edited in a vital clue: The method being called, the one that somehow provokes this exception, is defined using [DllImport(...)].

Since the exception is thrown at the end of the method that calls this external function, most likely the signature specified in C# does not match the signature of the function compiled into this dll.

This may lead to the stack becoming corrupted when you call it. Symptoms of such corruption may include:

  • Odd exceptions when the method call returns
  • Odd exceptions after the method call returned
  • Data corruption, like stack variables overwritten, etc.

Since you've now verified that after changing the MoveResult structure, the exception has gone away, it is safe to say that this is what happened.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825