在C#中更改对象的内存地址
Change the memory address of an object in C#
是否可以在 C# 中更改对象的内存地址?我想要的示例:
unsafe public Program {
public struct Foo
{
int a;
int b;
}
static void Main(string[] args){
Foo foo= new Foo();
fixed(Foo *foo_ptr=&foo) //I know I can get the object pointer here.
Foo foo2= new Foo();
fixed(&foo2=foo_ptr) //How I can do this?
}
}
我在尝试最后一个 fixed
时遇到了这个错误:
You can only take the address of an unfixed expression inside of a fixed statement initializer csharp(CS0212)
有人可以帮助我吗?谢谢。
编辑:
说来话长,为什么我要更改内存地址而不仅仅是写 foo2=foo;
。这就是为什么我想知道是否可能?
只是为了将此问题标记为 已回答 有用,我再次将我的评论粘贴到此处。
It won't be easy to do so.
Because in .Net, GC must track the address of all of the variables to de-allocate the pointer, after releasing the last anchor of the variable.
Also, it's illegal because each application has it's own Application Domain and by default, no application is allowed to access to out of its boundary.
请考虑将问题标记为已回答。
非常感谢。
假设p
是指向共享内存的指针,可以使用ref
关键字创建引用。
byte* p;
ref Foo foo = ref *(Foo*)p;
//foo.a, foo.b
是否可以在 C# 中更改对象的内存地址?我想要的示例:
unsafe public Program {
public struct Foo
{
int a;
int b;
}
static void Main(string[] args){
Foo foo= new Foo();
fixed(Foo *foo_ptr=&foo) //I know I can get the object pointer here.
Foo foo2= new Foo();
fixed(&foo2=foo_ptr) //How I can do this?
}
}
我在尝试最后一个 fixed
时遇到了这个错误:
You can only take the address of an unfixed expression inside of a fixed statement initializer csharp(CS0212)
有人可以帮助我吗?谢谢。
编辑:
说来话长,为什么我要更改内存地址而不仅仅是写 foo2=foo;
。这就是为什么我想知道是否可能?
只是为了将此问题标记为 已回答 有用,我再次将我的评论粘贴到此处。
It won't be easy to do so. Because in .Net, GC must track the address of all of the variables to de-allocate the pointer, after releasing the last anchor of the variable. Also, it's illegal because each application has it's own Application Domain and by default, no application is allowed to access to out of its boundary.
请考虑将问题标记为已回答。 非常感谢。
假设p
是指向共享内存的指针,可以使用ref
关键字创建引用。
byte* p;
ref Foo foo = ref *(Foo*)p;
//foo.a, foo.b