目标:获得一个 Windows Phone 7 名称(如“我的 Windows Phone”)。
以上代码以 C++ 形式提供,我想将其更改为 C#。一个原因是因为我只有 Visual Studio 2012 Express,它不允许我将 C++ 与 Windows Phone 项目一起使用,而且我已经购买了 VS2013,为此买不起 VS2012。另一个原因是 C++ 中有超过 150 个依赖文件,代码太多了!
所以,我的第一次尝试:(灵感来自http://www.experts-exchange.com/Programming/Languages/.NET/Q_21014265.html)
[StructLayout(LayoutKind.Sequential)]
internal struct WSAData
{
public short wVersion;
public short wHighVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
public string szDescription;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
public string szSystemStatus;
public short iMaxSockets;
public short iMaxUdpDg;
public int lpVendorInfo;
}
[DllImport("wsock32.dll")]
internal static extern int WSAStartup(
[In] short wVersionRequested,
[Out] out WSAData lpWSAData
);
[DllImport("wsock32.dll")]
internal static extern int WSACleanup();
public static void Test()
{
WSAData dummy;
WSAStartup(0x0002, out dummy);
// TODO: more stuff
WSACleanup();
}
它失败并WSAStartup(0x0002, out dummy);
出现异常:
MyLibrary.dll 中出现了“System.MethodAccessException”类型的第一次机会异常
附加信息:尝试访问该方法失败:MyLibrary.WSAStartup(System.Int16, .WSAData&)
我的第二次尝试:(灵感来自Convert service name to port)
[StructLayout(LayoutKind.Sequential)]
public struct WSAData
{
public short version;
public short highVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
public string description;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
public string systemStatus;
public short maxSockets;
public short maxUdpDg;
public IntPtr vendorInfo;
}
internal static class NativeMethods
{
[DllImport("Ws2_32.dll")]
public static extern Int32 WSAStartup(short wVersionRequested, ref WSAData wsaData);
[DllImport("Ws2_32.dll")]
public static extern Int32 WSACleanup();
}
public static void Test()
{
WSAData dummy = new WSAData();
NativeMethods.WSAStartup(0x0202, ref dummy);
// TODO: more stuff
NativeMethods.WSACleanup();
}
它失败并NativeMethods.WSAStartup(0x0202, ref dummy);
出现异常:
MyLibrary.dll 中出现了“System.MethodAccessException”类型的第一次机会异常
附加信息:尝试访问方法失败:MyLibrary+NativeMethods.WSAStartup(System.Int16, .WSAData&)
有什么建议可以让它在 WP7 设备上运行吗?
[编辑:这篇文章还建议版本 0x0101 使用 WSAStartup() 的可能性]