C#中的不安全结构



我想通过创建简单的结构(Vector,Particle(来尝试c#的不安全"功能"。

情况

我有这两个结构,想把位置和速度向量注入到我的粒子结构中。作为一个测试,我想打印出位置的X值,但不知怎么的,我得到了随机值。

我这里有以下代码

矢量

public readonly struct Vector
{
public int X { get; }
public int Y { get; }
public Vector(int x, int y)
{
X = x;
Y = y;
}
}

粒子

public unsafe struct Particle
{
private Vector* mPosition;
private Vector* mVelocity;
public Particle(Vector position, Vector velocity = default)
{
mPosition = &position; // here is x 10
mVelocity = &velocity;
}
public int GetPosX()
{
return mPosition->X; // but here not
}
}

程序

public class Program
{
private static void Main(string[] args)
{
var pos = new Vector(10, 5);
var obj = new Particle(pos);
Console.WriteLine(obj.GetPosX()); // prints random value
}
}

问题

它打印一个随机值,而不是10。

class Program {
static void Main (string [ ] args) {
unsafe {
Vector pos = new Vector(10, 5);
Particle obj = new Particle(&pos);
// &pos is at position 0xabcdef00 here.
// obj.mPosition has a different value here. It points to a different address? Or am I misunderstanding something
Console.WriteLine(obj.GetPosX( ));
}
}
}
public struct Vector {
public int X;
public int Y;
public Vector (int x, int y) {
X = x;
Y = y;
}
}
public unsafe struct Particle {
private Vector* mPosition;
public Particle (Vector *position) {
mPosition = position; // here is x 10
}
public int GetPosX ( ) {
return mPosition->X; // still 10 here
}
}

这对我有用。请不要问我为什么会这样。你会注意到我没有改变那么多。只是用*pos而不是pos调用Particle。出于某种原因,这解决了问题。你必须用unsafe包装代码,然后明显地更改Particle的构造函数。

我可以推测它为什么有效,但我宁愿不这样做。也许由于某种原因,当您将pos作为参数传递时,指针会发生变化?

您无法获取具有正确值的ref。

创建一个变量,如int posX=10;

你可以用变量引用。获取编译时引用并读取运行时引用。

不要使用没有固定值的指针。C#堆栈的性能非常好。你不需要这个。

通常指针与链接(C/Cpp动态库链接等(一起使用。如果您有大的structs(30字节及以上(,那么您可以使用ref参数标记。

最新更新