如何为WlanHostedNetworkSetProperty函数设置C#结构

时间:2015-10-02 17:07:08

标签: c# pinvoke marshalling

来自Microsoft文档:

DWORD WINAPI WlanHostedNetworkSetProperty(
  _In_       HANDLE                      hClientHandle,
  _In_       WLAN_HOSTED_NETWORK_OPCODE  OpCode,
  _In_       DWORD                       dwDataSize,
  _In_       PVOID                       pvData,
  _Out_opt_  PWLAN_HOSTED_NETWORK_REASON pFailReason,
  _Reserved_ PVOID                       pvReserved
);

我的实施

     [DllImport("Wlanapi.dll", EntryPoint = "WlanHostedNetworkSetProperty")]
        public static extern uint WlanHostedNetworkSetProperty(
             IntPtr hClientHandle,
             WLAN_HOSTED_NETWORK_OPCODE OpCode,
             uint dwDataSize,
             IntPtr pvData,
             [Out] out WLAN_HOSTED_NETWORK_REASON pFailReason,
             IntPtr pReserved
        );

如果我只是尝试启用或禁用Wlan,这可以正常工作。但是,当我尝试设置ssid和我遇到的对等数时,因为pvData需要是指向以下结构的指针:

来自Microsoft文档:

typedef struct _WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS {
  DOT11_SSID hostedNetworkSSID;
  DWORD      dwMaxNumberOfPeers;
} WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS, *PWLAN_HOSTED_NETWORK_CONNECTION_SETTINGS;

typedef struct _DOT11_SSID {
  ULONG uSSIDLength;
  UCHAR ucSSID[DOT11_SSID_MAX_LENGTH];
} DOT11_SSID, *PDOT11_SSID;

这是我对两种结构的实现:

    public struct WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS
    {
        public DOT11_SSID hostedNetworkSSID;
        public UInt32 dwMaxNumberOfPeers;
    }

    public struct DOT11_SSID 
    {
        public UInt32 uSSIDLength;
        public byte[] ucSSID;
    }

最后,这就是我打电话的方式:

            APCreator.WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS networkSetting = new APCreator.WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS();
            networkSetting.dwMaxNumberOfPeers = 5;
            networkSetting.hostedNetworkSSID = new APCreator.DOT11_SSID();
            networkSetting.hostedNetworkSSID.ucSSID = new byte[10];
            //Populate ucSSID with network name

            networkSetting.hostedNetworkSSID.uSSIDLength = 10;


            int size = Marshal.SizeOf(networkSetting);
            IntPtr pNetworkSetting = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(networkSetting, pNetworkSetting, true);
            APCreator.WlanHostedNetworkSetProperty(HANDLE, APCreator.WLAN_HOSTED_NETWORK_OPCODE.wlan_hosted_network_opcode_connection_settings, (uint)size, pNetworkSetting, out ReasonEnum, Nill).ToString();

错误原因返回:wlan_hosted_network_reason_isufficient_resources

问题是:如何设置这些结构?

1 个答案:

答案 0 :(得分:1)

您的DOT11_SSID结构不正确。试试这个:

public struct DOT11_SSID
{
    public UInt32 uSSIDLength;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = DOT11_SSID_MAX_LENGTH)]
    public byte[] ucSSID;
}

如果没有MarshalAs属性,它会尝试将ucSSID字段封送为指向字节数组的指针,而不是将值包含在struct中。

DOT11_SSID_MAX_LENGTH替换为标题中定义的任何值。