我想通过创建简单的结构(向量,粒子)来尝试c#不安全的“特性”。
SITUATION
我有这两个结构,想要把位置和速度矢量注入到我的粒子结构中。作为一个测试,我想打印出位置的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。
发布于 2020-04-15 14:38:43
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调用粒子。因为某种原因解决了问题。然后,您必须用不安全包装代码,并明显地更改粒子的构造函数。
我可以推测它为什么会起作用,但我宁愿不这样做。当您将pos作为参数传递时,由于某种原因,指针可能会发生变化吗?
发布于 2020-04-15 14:28:22
你不能以正确的价值接受裁判。
创建一个变量,如int posX = 10;
你可以用变量来表示引用。使用编译时引用并读取运行时引用。
不要使用没有固定的指针。C#堆栈性能非常好。你不需要这个。
指针通常与链接一起使用(C/Cpp动态库链接等)。如果您有较大的结构(30字节以上),那么您可以使用ref参数标记。
https://stackoverflow.com/questions/61230784
复制相似问题