I'm just returning back to C# after an extended period of C++ and Qt. I'm currently stumped by what I would have thought to be a very simple problem.
I have a struct:
struct FontGlyph {
public uint codepoint;
public byte[] bmp;
...
}
And an array of such structs:
FontGlyph[] glyphs = new FontGlyph[100];
Now, I have a couple of functions which set up and modify the fields in the structs:
static void ConvertFont(Font fnt) {
...
if (fnt.IsSpaceCharacter) {
glyphs[idx].codepoint = 0x00FF;
glyphs[idx].bmp = null;
}
else {
RenderFontGlyph(glyphs[idx]);
// glyphs[idx].bmp is NOT ok here - it is null!
}
...
}
static void RenderFontGlyph(FontGlyph glyph) {
...
glyph.bmp = new byte[256];
// bmp is fine here, and can be populated as a normal array
...
}
This isn't a particularly great snippet of code, however, in the RenderFontGlyph function, I can see that the bmp array is allocated correctly yet when the RenderFontGlyph function returns, upon inspection of the glyphs[idx] variable, bmp is back to null.
I appreciate I'm probably doing something n00bish but its been a while. Am I a victim of garbage collection or am I being stupid? It had occurred to me that the struct was being passed into the RenderFontGlyph function by-value rather than by-ref but this also makes no difference!
structs, when passed by value (which is the default), are being copied, so you're modifying a copy ofglyphs[idx]in your method and it has no effect on the instance stored in the array. Pass the value by reference to make it work.refhowever when the RenderFontGlyph returns, thebmpfield is still null - even though it is correctly initialized in the function.