weird Array.ConvertAll
[StructLayout(LayoutKind.Sequential)]
public struct RecognizeResult
{
/// float
public float similarity;
/// char*
[MarshalAs(UnmanagedType.LPStr)]
public StringBuilder fileName;
}
RecognizeResult[] results = new Rec开发者_高级运维ognizeResult[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?
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);
}
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.
精彩评论