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;    
    }
}

The problem I am facing here is how they can access the next structure element

*(post + i)

I'm not sure how all this will be done in C #, and moreover, I don’t want to use unsafe pointers to C #, but something alternates between it.

Thank!

+5
source share
3 answers

You should replace structwith an array of 5 elements.

If you want, you can wrap an array in a class with five properties.

edit...

"Wrap", , , , , ( use here = 'wrap a object'). . "" -.

:

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 ...

}
+3

C , , abc struct, . #, , . , #, :

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.

+2

The thought of C codes is not good for C #. C code is based on the assumption that the fields of the structure will be sequentially placed in memory in the order determined by the fields. The above looks like homework or a contrived example. Without knowing the real intention, it is hard to imagine a concrete example in C #.

other examples here involve changing the data structure, but if you cannot / do not want to do this, you can use reflection in combination with an array of objects of type struct to achieve the same result as above.

void Hello(abc currentObj){
  var fields = typeof(abc).GetFields();
  for(var i = 0;i<fields.Length;i++){
    fields[i].SetValue(currentObj,i);
  }
}
+1
source

All Articles