2

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?

Tobag
  • 170
  • 1
  • 10
  • 1
    Hint: It is so much easier to use C++/CLI for InterOp ;-) – D.R. Jul 30 '13 at 18:32
  • 1
    For everything else, see http://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-sharp-from-a-byte-array – D.R. Jul 30 '13 at 18:33

2 Answers2

2

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;
};
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
0

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;
};
Justin
  • 4,002
  • 2
  • 19
  • 21
  • This cannot work imho, as muc0 to muc2 are only ONE byte on the C++ side. Don't know about the automatic COM-conversion, but I do think, COM sticks to this and you must use MarshalAs as in the linked question (see my comment). – D.R. Jul 30 '13 at 19:38
  • Thanks a lot with http://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-sharp-from-a-byte-array I was able to get it running! – Tobag Jul 30 '13 at 19:54