开发者

C++/C# Array shift equivilents

开发者 https://www.devze.com 2023-03-19 07:02 出处:网络
I\'m trying to convert some code from C++ into C# and I\'m not sure if these two statements would be equivalent.

I'm trying to convert some code from C++ into C# and I'm not sure if these two statements would be equivalent.

C++ (the source):

float* df = new float[ length ]  // length is a previously initialized int
int coefIND = 0;
do
{
    float* const df2 = df + coefIND;开发者_高级运维
    // some element reassignments such as df2[1] = x[...] * y[...];
    coefIND += 4;
}
while(coefINF < length);
delete[] df;  // this occurs much later though

C# (translation?):

float[] df = new float[ length ]
int coefIND = 0;
do
{
     Array.Copy(df, 0, df, coefIND, length);
     // some element reassignments such as df[1] = x[...] * y[...];
     coefIND += 4;
}
while(coefIND < length)

Thanks for the help, Greg


You haven't shown the C# definition of df2, but probably the best solution is to just add coefIND to each index in the body of the code, rather than copying to a temporary array (and back again afterward.) Unlike C++, safe C# does not allow you to store a pointer to an element inside an array.


If you are desperate to do this way you could use linq.

df2 = df.Skip(coefIND).ToArray();

However I believe that in C++ you are assuming the size of a float is 4 bytes (hence the increment by 4.

A far better implementation of the loop would just be;

for (var coefIND=0;coefIND<df.length;coefIND++) {
  // some element reassignments such as df[coefIND] = x[...] * y[...];
}

Your code is mentioning df[1] in the comment, arrays are zero index so the way you had used this would have accessed memory past the end of your array.


The translation that you have provided is highly inefficient, as it requires copying of the contents of the array many times. The expression df[ x ] in C++ is equivalent to *(df + x), and you can apply that conversion to the code to obtain:

float[] df = new float[ length ]
int coefIND = 0;
do
{
     // some element reassignments such as:
     df[ coefIND + 1] = x[... ] * y[...];
     coefIND += 4;
}
while(coefIND < length);

Note that with all of the operations in the loop being unrolled, chances are that you will have a few extra additions (compared to the C++ code) but overall the performance should be almost the same.

0

精彩评论

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