Tobag
Tobag

Reputation: 178

How to convert C/C++ struct to C#

I want to write a plugin for a program. The program can only use C/C++ *.dll libraries. I want to write my plugin in C# though, so I thought I could just call my C# functions from the C++ dll through COM. This works fine but now I need to access a struct provided by the original program. In C++ this struct looks like this:

struct asdf{
char            mc[64];
double          md[10];

unsigned char   muc[5];

unsigned char   muc0 : 1;
unsigned char   muc1 : 1;
unsigned char   muc2 : 6;
unsigned char   muc3;

another_struct st;
};

To be able to pass that struct to C# as a parameter I tried to built exactly the same struct in C#. I tried the following, but it gives me an access violation:

struct asdf{
char[]            mc;
double[]          md;

byte[]   muc;

byte   muc0;
byte   muc1;
byte   muc2;
byte   muc3;

another_struct st;
};

What do I have to change?

Upvotes: 2

Views: 2340

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134125

If you want the arrays inline, you need to use fixed-size buffers. I'm assuming that the C char is a byte. The code to handle muc0, muc1, etc. will require some custom properties. You treat the entire thing like a byte.

struct asdf
{
    public fixed byte    mc[64];
    public fixed double  md[10];

    public fixed byte    muc[5];

    private byte         mucbyte;

    // These properties extract muc0, muc1, and muc2
    public byte muc0 { get { return (byte)(mucbyte & 0x01); } }
    public byte muc1 { get { return (byte)((mucbyte >> 1) & 1); } }
    public byte muc2 { get { return (byte)((mucbyte >> 2) & 0x3f); } }

    public byte muc3;

    public another_struct st;
};

Upvotes: 2

Justin
Justin

Reputation: 4072

I would change it slightly, use a string and make sure you init your arrays to the same size used in the C++ code when you use the struct in your program.

struct asdf{
string            mc;
double[]          md;

byte[]            muc;

byte              muc0;
byte              muc1;
byte              muc2;
byte              muc3;
};

Upvotes: 0

Related Questions