简体   繁体   English

通过P / Invoke在C#中使用C / C ++结构

[英]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: 我正在使用P / Invoke迈出第一步,并尝试代表这些C / C ++结构:

#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#: 在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: 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;

Final struct looks OK to me, the only change you should do is how your boolean_T is marshaled. 最终的结构对我来说还可以,您唯一要做的更改是如何boolean_T Default C-style bool is one byte signed integer so it must be marshaled as I1 . 默认的C样式bool是一个字节的有符号整数,因此必须将其封送为I1 You declared boolean_T it as unsigned char so it should be U1 : boolean_T声明为unsigned char因此应为U1

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM