C#struct无参数构造函数?看看我需要完成什么 [英] C# Struct No Parameterless Constructor? See what I need to accomplish

查看:1180
本文介绍了C#struct无参数构造函数?看看我需要完成什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用结构传递到非托管DLL,因此 -

I am using a struct to pass to an unmanaged DLL as so -

[StructLayout(LayoutKind.Sequential)]
        public struct valTable
        {
            public byte type;
            public byte map;
            public byte spare1;
            public byte spare2;
            public int par;
            public int min;
            public byte[] name;
            public valTable()
            {
                name = new byte[24];
            }
        }


$ b $ p <上述代码无法编译,因为VS 2005会投诉Structs不能包含显式无参构造函数。为了将这个结构传递给我的DLL,我必须传递一个结构体数组,如 valTable [] val = new valTable [281];

我想做的是当我说 new 时,构造函数被调用,它创建一个字节数组,因为DLL在每个维度中寻找大小为24的字节数组。

What I would like to do is when I say new, the constructor is called and it creates an array of bytes like I am trying to demonstrate because the DLL is looking for that byte array of size 24 in each dimension.

如何实现这个?

推荐答案

您可以使用固定大小缓冲区 - 我怀疑你真正想要的,以便在结构中获取数据inline(而不是一个数组在其他地方的引用)。

You can use a fixed size buffer - which I suspect you really want anyway, so as to get the data "inline" in the struct (rather than a reference to an array elsewhere).

public fixed byte name[24];

您需要将结构声明为不安全。

You'll need to declare the struct as unsafe as well though.

请注意,任何需要调用静态方法或提供任何自定义构造函数的解决方案都会失败,因为您的明确目标是能够创建这些结构体的数组。

Note that any "solution" which requires calling a static method or providing any kind of custom constructor will fail with your explicit goal of being able to create an array of these structs.

这篇关于C#struct无参数构造函数?看看我需要完成什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆