使用PInvoke时,什么时候应使用类,何时要求输入指向NAME结构的指针的结构?

时间:2018-09-16 21:45:05

标签: c# .net struct pinvoke

很抱歉,问题还没解决。在C#中使用PInvoke时,某些函数需要将数据填充的结构,但是据我所知,某些函数仅在以C#形式将所述结构写为类时才起作用,因此您可以使用public struct StructName代替做public class StructName

如果您听不懂我的意思,可以尝试运行此代码,看看会发生什么

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
public static extern void GetSystemInfo([In, Out] SystemInfoStruct lpSystemInfo);

[DllImport("kernel32.dll")]
public static extern void GetSystemInfo([In, Out] SystemInfoClass lpSystemInfo);

[StructLayout(LayoutKind.Sequential)]
public struct SystemInfoStruct
{
    public ushort wProcessorArchitecture;
    private ushort wReserved;
    public uint dwPageSize;
    public IntPtr lpMinimumApplicationAddress;
    public IntPtr lpMaximumApplicationAddress;
    public IntPtr dwActiveProcessorMask;
    public uint dwNumberOfProcessors;
    private uint dwProcessorType;
    public uint dwAllocationGranularity;
    public ushort wProcessorLevel;
    public ushort wProcessorRevision;
}

[StructLayout(LayoutKind.Sequential)]
public class SystemInfoClass
{
    public ushort wProcessorArchitecture;
    private ushort wReserved;
    public uint dwPageSize;
    public IntPtr lpMinimumApplicationAddress;
    public IntPtr lpMaximumApplicationAddress;
    public IntPtr dwActiveProcessorMask;
    public uint dwNumberOfProcessors;
    private uint dwProcessorType;
    public uint dwAllocationGranularity;
    public ushort wProcessorLevel;
    public ushort wProcessorRevision;
}

class Program
{
    static void Main()
    {
        //SystemInfoClass infoClass = new SystemInfoClass();
        //GetSystemInfo(infoClass);

        //SystemInfoStruct infoStruct = new SystemInfoStruct();
        //GetSystemInfo(infoStruct);
    }
}

至少对我来说,使用结构失败并返回带有读/写访问被拒绝的错误,另一方面,使用有效的类。 因此,问题是,什么时候应该使用结构,什么时候应该为PInvoke函数使用类,还是应该始终使用类? 谁知道,也许我忽略了一些重要的事情。

1 个答案:

答案 0 :(得分:1)

通常,您应该使用https://pinvoke.net/说的内容。如果它说需要用struct来调用,则传递一个struct。如果它说需要用class来调用,则传递一个class

现在,如果您想危险地生活,可以尝试将classstruct互换,但是要注意,通过class并不完全等同于通过struct;相反,它等效于struct传递ref

相关问题