当我尝试将从MathNet 库中的 Matrix 类型派生的类型的属性 与 nullptr 进行比较时,我遇到了一个奇怪的 NullReferenceException。
我想编写一个带有类转换的 C++/CLI 类库,它派生自 MathNet::Numerics::LinearAlgebra::Matrix,它应该将 3D 空间中的位置表示为齐次坐标中的 4x4 矩阵。因为我希望能够设置相对于其他位置的位置,所以我有一个属性Transformation^ parent
。通过if(parent == nullptr){ ... }
我想测试,如果当前的 Transformation 有一个父级,但我得到这个异常符合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 类如下所示:
/// 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
而不是 派生 Transformation 时ref class Transformation : Matrix
,一切正常,也是。
现在它变得非常奇怪。我想在 C#-Application 中使用我的类库。调用t.DoSomething()
Transformation t 会引发 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");
}
这可能来自哪里的任何建议?我真的很纳闷……