cs0815
cs0815

Reputation: 17388

C/C++ struct in C# via P/Invoke

I am taking my first steps using P/Invoke and try to represent these C/C++ structs:

#ifndef struct_emxArray_char_T_1024
#define struct_emxArray_char_T_1024
struct emxArray_char_T_1024
{
    char_T data[1024];
    int32_T size[1];
};

#ifndef typedef_e_struct_T
#define typedef_e_struct_T
typedef struct
{
    emxArray_char_T_1024 value1;
    real_T value2;
    uint32_T value3;
    boolean_T value4;
} e_struct_T;

using this in C#:

[StructLayout(LayoutKind.Sequential)]
class emxArray_char_T_1024
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
    public string data;
    [In, MarshalAs(UnmanagedType.I4)]
    public int size;
}

StructLayout(LayoutKind.Sequential)]
class e_struct_T
{
    emxArray_char_T_1024 value1;
    double value2;
    uint value3;
    bool value4;
}

Does this look sufficient? I am not too sure about the comments like this in the tutorial:

compile with: /target:module

PS:

The above 'types' seem to be defined like this:

typedef double real_T;
typedef unsigned int uint32_T;
typedef unsigned char boolean_T;
typedef char char_T;
typedef int int32_T;

Upvotes: 0

Views: 249

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67080

Final struct looks OK to me, the only change you should do is how your boolean_T is marshaled. Default C-style bool is one byte signed integer so it must be marshaled as I1. You declared boolean_T it as unsigned char so it should be U1:

[StructLayout(LayoutKind.Sequential)]
class e_struct_T
{
    emxArray_char_T_1024 value1;
    double value2;
    uint value3;

    [MarshalAs(UnmanagedType.U1)] 
    bool value4;
}

Upvotes: 1

Related Questions