[英]Need help converting this snippet from c to c#
typedef struct {
int e1;
int e2;
int e3;
int e4;
int e5;
} abc;
void Hello(abc * a, int index)
{
int * post = (&(a->e1) + index);
int i;
for(i = 0; i<5; i++)
{
*(post + i) = i;
}
}
我在這里面臨的問題是他們如何能夠訪問結構中的下一個元素
*(post + i)
我不確定如何在 C# 中完成所有這些操作,此外,我不想在 C# 中使用不安全的指針,但可以替代它。
謝謝!
您應該將struct
替換為 5 個元素的數組。
如果需要,可以將數組包裝在具有五個屬性的 class 中。
當您說“包裝”時,它通常意味着在 class 中寫入屬性,這些屬性設置或獲取單個變量、數組元素或另一個 class 的成員的值,該 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 的實例位於您的 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 '包裝一個對象')。 對於分離關注點和連接多個對象的功能非常有用。 從技術上講,所有簡單的屬性都只是“包裝”它們的私有成員變量。
每個評論的示例:
class test
{
int[] e = new int[5];
public void Hello(int index)
{
for (int i = 0; i <= 4; i++) {
// will always happen if index != 0
if (i + index > 4) {
MsgBox("Original code would have overwritten memory. .Net will now blow up.");
}
e[i + index] = i;
}
}
public int e1 {
get { return e[0]; }
set { e[0] = value; }
}
public int e2 {
get { return e[1]; }
set { e[1] = value; }
}
//' ETC etc etc with e3-e5 ...
}
C 代碼的問題在於,如果 index 大於 0,它將超出 abc 結構的末尾,從而覆蓋隨機 memory。 這就是為什么 C#(一種更安全的語言)不允許此類事情發生的原因。 我在 C# 中實現您的代碼的方式是:
struct abc
{
public int[] e;
}
void Hello(ref abc a, int index)
{
a.e = new int[5];
for (int i = 0; i < 5; ++i)
a.e[index + i] = i;
}
請注意,如果 index > 0,您將得到一個越界異常,而不是像在 C 代碼段中那樣可能無聲的 memory 覆蓋。
C 代碼背后的想法不適合 C#。 C 代碼是基於這樣的假設,即結構的字段將按照定義字段的順序依次放置在 memory 中。上面看起來像是作業或人為的示例。 在不了解真實意圖的情況下,很難在 C# 中給出具體示例。
此處的其他示例建議更改數據結構,但如果您不能/不想這樣做,則可以將反射與 struct 類型的對象數組結合使用來完成與上述相同的結果。
void Hello(abc currentObj){
var fields = typeof(abc).GetFields();
for(var i = 0;i<fields.Length;i++){
fields[i].SetValue(currentObj,i);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.