0

How would you marshall this nested array of structure in C#?

C struct:

typedef struct
{
    unsigned int appVersionNumber;
    unsigned int networkId;
    struct
    {
        int code;
        int endDate;
    } profiles[4];
} CardEnvHolder;

My C# attempt:

[StructLayout(LayoutKind.Sequential)]
unsafe struct CardEnvHolder
{
    public uint appVersionNumber;
    public uint networkId;
    public Profiles[] profiles;
}

[StructLayout(LayoutKind.Sequential)]
struct Profiles 
{
    public int code;
    public int endDate;
}

C# Main:

unsafe 
{
    CardEnvHolder envhold = new CardEnvHolder();
    void* ptr = (void*)&envhold; //Error here
    EnvHolderTest(ptr);
    Console.WriteLine(envhold.profil[1].code);
}

Unfortunately I get the error CS0208 "Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')"

As requested,

EnvHolder C function:

void EnvHoldInit(CardEnvHolder* envhold)
{
    envhold->appVersionNumber = 4;
    envhold->networkId = 8;
    envhold->profiles[1].code = 84;
    printf("%d\n", envhold->profiles[1].code);
    envhold->profiles[1].code++;
}

EXPORT void EnvHolderTest(void* envhold)
{
    EnvHoldInit(envhold);
}

EnvHolder C# prototype:

[DllImport("Sandbox.dll", CallingConvention = CallingConvention.Cdecl)]
extern static unsafe void EnvHolderTest([In, Out] void* envhold);
16
  • Are you asking about C# or C — they are radically different languages and should seldom both be tagged in the same question. When they are both relevant, the question will explicitly ask about how to map a C structure into C# or vice versa, or something similar. Marshalling is normally a precursor to sending data over the network, or storing it in a file. What are you trying to do, and which language are you trying to do it in? Commented Jun 30, 2021 at 14:46
  • @JonathanLeffler Yes, I am looking to marshall this C struct in C#, sorry for the misunderstanding Commented Jun 30, 2021 at 14:47
  • 1
    There is nothing non-trivial in declaring this structure in C#. What exactly are having problems with? Commented Jun 30, 2021 at 14:49
  • 1
    Yes, you can. Just add [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] to public Profiles[] profiles. That unsafe portion also looks unnecessary, please show EnvHolderTest. Commented Jun 30, 2021 at 14:56
  • 1
    It might feel easier but it's wrong. Just use standard marshalling EnvHolderTest(ref envhold) after setting the correct MarshalAs Commented Jun 30, 2021 at 15:12

0

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.