C# 类变量、不安全/固定指针赋值的问题
好吧,我现在已经进入了一些圈子,尽管我可能会问这个问题。我有一个类,可以说是 A 类,其中包含一些成员变量和函数。我有一部分不安全的代码,我需要将成员变量作为引用传递给它,并为该引用变量分配一些值。
Class A
{
int v1;
int v2;
....
public unsafe void Method(ref V)
{
// Here I need to have something like a
// pointer that will hold the address of V (V will be either v1 or v2)
// Assign some values to V till function returns.
int *p1 = &V
fixed (int *p2 = p1)
{
// Assign values.
}
}
}
问题是函数一返回,值就不会存储在 v1 或 v2 中。那么我该如何解决这个问题呢?
谢谢!
Ok, I have been into some circles now and though I might ask this at SO. I have a class lets say Class A with some member variables and functions. I have a portion of unsafe code to which I need to pass the member variable as a reference and assign some values to that reference variable.
Class A
{
int v1;
int v2;
....
public unsafe void Method(ref V)
{
// Here I need to have something like a
// pointer that will hold the address of V (V will be either v1 or v2)
// Assign some values to V till function returns.
int *p1 = &V
fixed (int *p2 = p1)
{
// Assign values.
}
}
}
The problem is as soon as the function returns, the values are not stored in either v1 or v2. So how do I fix this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
V
已经是按引用传递的,因此除非您有特定的想法:只需分配给V
即可。请注意,如果此处涉及多个线程,您可能需要易失性
、互锁
或同步(例如lock
) - 这适用于all< /em> 访问成员(读或写)。V
is already pass-by-reference, so unless you have something specific in mind: just assign toV
. Note that if multiple threads are involved here you might needvolatile
,Interlocked
or synchronisation such aslock
- and this applies to all access to the member (read or write).您可以简单地传递类变量(默认情况下通过引用)并访问其公共字段/属性。或者您可以:
我无法想象一个令人信服的理由(根据您提供的详细信息)实际上需要修复内存中的 v1 和 v2 并获取它们的实际地址以提供给该函数。除非我理解错了?
编辑:
也许您的赋值语句缺少“*”?但同样,为什么不能直接分配给变量呢?
You could simply pass the class variable (which would be by reference by default) and access its public fields/properties. Or you could:
I can't imagine a compelling reason (with the details you gave) to actually need to fix v1 and v2 in memory and get their actually addresses to give to the function. Unless I've misunderstood?
EDIT:
Perhaps your assignment statements are missing a '*'? But again, why can't you just assign to the variables directly?