看看我需要完成什么

看看我需要完成什么

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

问题描述

我正在使用一个结构体来传递给一个非托管的 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];
            }
        }

上面的代码将无法编译,因为 VS 2005 会抱怨结构不能包含显式无参数构造函数".为了将此结构传递给我的 DLL,我必须像这样传递一个结构数组 valTable[] val = new valTable[281];

The code above will not compile because VS 2005 will complain that "Structs cannot contain explicit parameterless constructors". In order to pass this struct to my DLL, I have to pass an array of struct's like so 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.

我怎样才能做到这一点?

How can I accomplish this?

推荐答案

您可以使用 固定大小的缓冲区 - 我怀疑你真的想要它,以便在结构中内联"数据(而不是对其他地方的数组的引用).

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# 结构没有无参数构造函数?看看我需要完成什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:21