加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#到C数组?

发布时间:2020-12-16 01:58:37 所属栏目:百科 来源:网络整理
导读:我提供了一个库,我知道使用C语言. 我这样导入了DLL: [DllImport(“pst”)] private static extern int pst_get_sensor(ref PSTSensor sensor); PSTSensor是一个结构,在C示例中它被定义为: struct PSTSensor{ char name[80]; /** Device name */ int id; /*
我提供了一个库,我知道使用C语言.
我这样导入了DLL:
[DllImport(“pst”)] private static extern int pst_get_sensor(ref PSTSensor sensor);
PSTSensor是一个结构,在C示例中它被定义为:

struct PSTSensor
{
        char    name[80];       /**< Device name */
        int     id;             /**< Device identifier (for other tracking interfaces */
        float   pose[16];       /**< Device pose estimate as row-major matrix */
        double  timestamp;      /**< Time the data was recorded */
};

问题是,除了Int和Double之外,它还使用Float,更重要的是数组.数组在C#和C之间有所不同.使用此结构调用pst_get_sensor(ref sensor)时;运行代码时,整个开发环境都崩溃了.

我目前在C#中使用这样的结构:

struct PSTSensor{
        public char[] name;
        public int id;
        public float[] pose;
        public double timestamp;
    }

我的问题是,我如何创建一个C理解并正确返回的数组?这甚至可能吗?

非常感谢提前,
斯迈利

解决方法

您的C#结构需要定义内联数组长度.并且名称字段最好在C#代码中声明为字符串.这使您更容易使用它.

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
struct PSTSensor
{
    [MarshalAs(UnmanagedType.ByValTStr,SizeConst = 80)]
    public string name;
    public int id;
    [MarshalAs(UnmanagedType.ByValArray,SizeConst = 16)]
    public float[] pose;
    public double timestamp;
}

struct layout属性在这里是可选的,因为它只是重新声明默认值.但是你可以选择保留它以明确你的意图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读