tags:

views:

47

answers:

2
[StructLayout(LayoutKind.Sequential)]
    public struct RecognizeResult
    {

        /// float
        public float similarity;

        /// char*
        [MarshalAs(UnmanagedType.LPStr)]
        public StringBuilder fileName;

    }


RecognizeResult[] results = new RecognizeResult[50];


Array.ConvertAll(results, r => r.fileName = new StringBuilder(50) );

But the element of results array is not changed, the fileName of every element is null after the ConvertAll(), what's wrong?

A: 

Array.ConvertAll returns a new array, it does not modify the existing one. You are not assigning the return of the method to anything:

var newArray = Array.ConvertAll(results, r => r.fileName = new StringBuilder(50));

Note this just creates an array of empty StringBuilders... but that's kinda outside the scope of the question since you haven't said what you're trying to accomplish.

Rex M
but it will return an array of string, and the desired effect still wont be achieved...
leppie
an array of stringbuilder rather (oops) :)
leppie
+1  A: 

If RecognizeResult was a class, then it would work.

It has nothing to do with the return value, which can be safely ignored.

The problem is that a copy of the RecognizeResult struct is passed to the converter function (which returns a StringBuilder incidentally). And hence you are not mutating the value you are thinking you are changing.

To do this properly, you would need to use an array:

for (int i = 0; i < results.Length; i++)
{
  results[i].fileName = new StringBuilder(50);
}
leppie