0

I am trying to use C++ code in my C# application. The following structure is created:

System.Runtime.InteropServices.StructLayout(
                        System.Runtime.InteropServices.LayoutKind.Sequential)]

public struct My_FSet
{
    public int Num;
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 100)]
    public uint[] Freqs;
}

I want to use it like an array in my code, like

My_FSet FSet = new My_FSet();
FSet.Freqs[0] = 1000;
FSet.Freqs[1] = 2500;
FSet.Freqs[3] = 3200;

But I get an error:

An unhandled exception of type 'System.NullReferenceException' occurred in MyApp.exe

Additional information: Object reference not set to an instance of an object.

It seems as if the array is not properly initialized, but I cannot do that in the struct, so how can I resolve this?

4
  • 1
    use constructor of struct to initialize array Commented Feb 5, 2016 at 12:22
  • @Ehsan Sajjad. Can you expand on that? Commented Feb 5, 2016 at 12:29
  • @Patrick Hoffman. I respectfully differ from the notion that this is a duplicate question. I am aware of null references and generally understand them well enough to get along. The issue here is, however, that the array is declared in the struct where I cannot initialize it. Or so it seems, because I get the error: Cannot have instance field initializers in structs when I try to do: public uint[] Freqs = new uint[100]; Commented Feb 5, 2016 at 12:34
  • Are you intending the array to be inline with the rest of the struct (making it (1+100) x 4 bytes long) or the array to be a separate object, with the struct containing the int field and a pointer to the array (thus only 8 or 12 bytes long)? C# only supports the latter case without some pretty egregious use of unsafe. Commented Feb 5, 2016 at 12:42

1 Answer 1

1

The problem is the array is never instantiated, hence the NullReferenceException. Since structs are a little different than classes, you have to give the information on creation of the object instead of assigning it later on.

Like this:

public struct My_FSet
{
    public readonly int Num;
    [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 100)]
    public readonly uint[] Freqs;

    public My_FSet(int num, uint[] freqs)
    {
        this.Num = num;
        this.Freqs = freqs;
    }
}

Then you can supply the array in the constructor:

My_FSet f = new My_FSet(1, new uint[] { 1, 2, 3 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.