當我嘗試將從Matrix類型派生的類型的屬性從MathNet library與nullptr進行比較時,發生了奇怪的NullReferenceException。使用Mathnet測試(m == nullptr)時的NullReferenceException矩陣類型
我想寫一個類轉換的C++/CLI類庫,它來自MathNet :: Numerics :: LinearAlgebra :: Matrix,它應該在三維空間中以齊次座標表示4x4矩陣中的位置。因爲我想能夠設置相對於其他頭寸的頭寸,我有一個屬性Transformation^ parent
。 通過if(parent == nullptr){ ... }
我想測試,如果當前的轉型有父,但我得到這個例外在符合if(parent == nullptr)
:
An unhandled exception of type 'System.NullReferenceException' occurred in MathNet.Iridium.dll
Additional information: Object reference not set to an instance of an object.
我的轉型類看起來是這樣的:
/// Transformation.h
using namespace MathNet::Numerics::LinearAlgebra;
using namespace System;
ref class Transformation : Matrix
//ref class Transformation : A
{
public:
Transformation(void);
Transformation^ parent;
void DoSomething();
};
/// Transformation.cpp
#include "StdAfx.h"
#include "Transformation.h"
Transformation::Transformation(void) : Matrix(4,4)
{
}
void Transformation::DoSomething()
{
if(parent == nullptr) // Produces NullReferenceException
{
Console::WriteLine("parent is nullptr");
}
Matrix^ m;
if(m == nullptr) // Produces NullReferenceException, too
{
Console::WriteLine("m is nullptr");
}
}
比較任何Matrix類型的變量,實際上是null,到nullptr似乎會拋出這個異常。如果正確初始化,沒有例外的,所以這個工作得很好:
Matrix^ m = gcnew Matrix(4,4);
if(m == nullptr) // works fine
{
Console::WriteLine("");
}
當汲取轉型,從一個不同的類,而不是ref class Transformation : A
ref class Transformation : Matrix
,一切正常了。
現在它變得非常奇怪。我想在C#應用程序中使用我的類庫。在轉換t上調用t.DoSomething()
將引發NullReferenceException。但是,如果我直接包含空值測試在我的C#應用程序,它的工作原理:
Transformation t = new Transformation();
// t.DoSomething(); // Throws NullReferenceException
if (t.parent == null) // OK!
{
Console.WriteLine("parent is null");
}
做同樣的在C++/CLI應用程序再次拋出NullReferenceException異常:
Transformation^ t = gcnew Transformation();
// t->DoSomething(); // Throws NullReferenceException
if(t->parent == nullptr) // Throws NullReferenceException
{
Console::WriteLine("parent is nullptr");
}
任何建議,其中本可能來自?我真的很疑惑...
我使用MathNet.Idirium Library, Version 2008.8.16.470
這通常表示* this *爲空。雖然不符合你的測試代碼。也許是版本問題。 –
如果這個(在這個上下文中的意思是t)是空的,我不能調用DoSomething()或者我錯了嗎?異常僅在DoSomething()內引發,而不是在調用時引發。 – richn
對於C++/CLI來說它不同,它不會生成代碼來確保* this *不像C#那樣是空的。當你嘗試訪問一個班級成員時,它會炸彈。可能很難診斷。但我同意你的測試使得這不太可能是這個問題的真正原因。在調試器中查看* this *以獲取任何提示。 –