C# help to C/C++ man: ref's and pointers.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hello
i am porting a program from C++ to C#
there are many read/writes of contigous regions in there
and i would like to save code
so 1st question is there a ready guide to problems with C++ translations

next, i would like to know whether there is a similar facility in C#
in c++/c i could take a pointer to an int and make it point anywhere
i could take address of any int, and could use it as pointer
e.g.
int x[200]
int* p_tens_of_ints
for (int i=0;i<20;i++){// i go by tens..
p_tens_sof_ints = x+i*(sizeof(int)*10)
for (int j=0;j<10;j++)
// use p_tens_of_ints as if it were a 20 members array
p_tens_of_ints[j]=20; // i could as well read it, nevermind


is there a way i could play with ref int[] the same way
if not what are the alternatives
note: i am on a compact framework, so i could not find a way of working with heapalloc etc
but maybe i am missing something.
anyway, in the case this has been documented somewhere, please be kind an point me to the direction
Thanks in advance
Max.
 
int x[200];
int* p_tens_of_ints;
for (int i=0;i<20;i++){// i go by tens...
p_tens_sof_ints = x+i*(sizeof(int)*10);
for (int j=0;j<10;j++){
// use p_tens_of_ints as if it were a 20 members array:
p_tens_of_ints[j]=20; // i could as well read it, nevermind.
}
}

If you need pointers, you can use pointers in an "unsafe" block (either a
block or on the whole method.) Unsafe basically means you can use pointers
in the block. To get an int pointer to the array, you would use the "fixed"
statement and use the pointer inside the fixed block - msdn doco has many
good examples. I have not analysed your code, but you can probably do this
in c# without pointers. In c# going to pointer does not always make
something faster or the marginal gain may be so small that is it may be
better just stay all managed and use array indexes, etc.
 
int x[200];
int* p_tens_of_ints;
for (int i=0;i<20;i++){// i go by tens...
p_tens_sof_ints = x+i*(sizeof(int)*10);

Off-topic, but you do realize that this actually accessed far beyond the
array? The following code:

p_tens_of_ints = x + i; // x is int*, i is int

would do the correct trick, actually. Pointers in C++ are already scaled
by the size of the type to which they refer.

Of course you could have done the same with indexing, and then it would
be much easier to port to C#.
 
Off-topic, but you do realize that this actually accessed far beyond the
array? The following code:

p_tens_of_ints = x + i; // x is int*, i is int

Sorry:

p_tens_of_ints = x + i * 10; // x is int*, i is int
 
Back
Top