开发者

C to C# code conversion - arrays as parameters

开发者 https://www.devze.com 2023-02-01 22:29 出处:网络
I\'m stuck on a recursive function in the C code (I did not write the C code).Here is the snippet I\'m converting:

I'm stuck on a recursive function in the C code (I did not write the C code). Here is the snippet I'm converting:

int makeroad(float x1, float y1, float x2, float y2, float var, float X[], float Y[], float prec)
{
//stuff
k+=makeroad(x,y,x2,y2,var,X+k,Y+k,prec);
}

I'm not entirely sure what this is doing. This is the only function in the C code with that name, so it's not an overloading issue. When it recursively calls itself, it is adding k to the X and Y arrays. 开发者_StackOverflow中文版Putting it in C# looks like this:

int makeroad (float x1, float y1, float x2, float y2, float var, float[] X, float[] Y, float prec)
    {
      //stuff
      k += makeroad(x, y, x2, y2, var, X + k, Y + k, prec);
    }

And Visual Studio is telling me that the X + k and Y + k are invalid. The original C code compiles and works fine in Visual C++ Express 2010. I don't think there was confusion between the upper and lower case x and y variables respectively. If there was, the code is working by sheer luck.

Any ideas?


In C you can "make" an array without the first k elements from an existing one just by passing the pointer to the k-th item (i.e. array+k), since arrays in C are passed by passing the location of their first element (such "new" array wouldn't be new at all, since it would refer to the same elements of the "original" one).

In C# this doesn't work since an array isn't handled just as a pointer to contiguous memory; if you want a quick fix, you can create a new array, copy the elements from the k-th to the end with Array.Copy and then pass this new array to the recursive function, but this is slow and doesn't work if the algorithm modifies the elements of the array (the modifications wouldn't be reflected in the other arrays, since they are now copies).

A better solution would be to pass the array as it is and k as a parameter, and make the routine start using the array from that position. You should achieve the same behavior without substantial speed penalties.


Arrays are passed by reference in C so the actual thing passed is a pointer to the beginning of the array. When you pass e.g. "X + k" you're passing a pointer to the sub-array starting at k.

I have no clue what C# does with array parameters, nor do I want to.


The X + k, and Y + k are pointers into the array. It allows you to "skip over" portions of the beginning of the array in the called function.

You can mix C code with other CLR code so you don't really have to convert this.

If you really feel you need to you might consider just passing X, Y, and k and rewriting the "stuff" to use k as a beginning offset into X and Y. The author uses C very efficiently in this case and it makes it difficult to port to another language.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号