0

I am trying to understand what is going on behind the curtain when I create an array with a constant size as below:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public float[] constArray;

I understand that I can use the fixed key word, but then ref is no longer an options, and all pointer operations must be inside a fixed expression.

What I am trying to do is parse an XML file and store at an given index in the array. So if there are 10 elements in the file I might set up the following:

for (int i = 0; i < 10; i++)
{
    readElement("element", ref constArray[i]);
}

However, constArray[i] is null.

Maybe a further instantiation is require, but then what is the point of marshalling. I thought marshalling created the object that ref operates on to create a reference.

I read through reference types and value types with out finding much information. I also read a few others such as ref and referencing arrays with out much progress.

I just can seem to find a resource that provides a good conceptual understanding. So any resources, as well as an answer, would be greatly appreciated.

Thank you, Blake

blakejwc
  • 55
  • 1
  • 8

1 Answers1

1

First of all - float cannot be null (if you want nullable float then use float?), so your problem might be in uninitialized array?

Overral MarshalAs

Indicates how to marshal the data between managed and unmanaged code.

Is that what you want? or is your goal as simple as following

float [] constArray = new float[10];

Are you sure that you need simple array - why not to use List<float>?

Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
JleruOHeP
  • 10,106
  • 3
  • 45
  • 71
  • After 5 years, I've forgotten exactly why I wanted to use an array. What I do remember was trying to imitate a c-style way of setting up the memory for the array such that I could dump values at the location of the pointer. I think my goal was as simple as `float [] constArray = new float[10];`. For the sake of understanding, why doesn't the reference to the ith index of constArray resolve? – blakejwc Apr 05 '18 at 19:51