.NET CF,Interop& GPS_DEVICE结构

时间:2009-10-07 19:45:10

标签: c# compact-framework interop

我正在尝试使用.NET CF 3.5中的GPS_DEVICE结构,并且我一直收到从GPSGetDeviceState调用返回的错误(87)。据我所知,87表示无效参数,但我不知道哪个参数无效!

任何人都可以告诉我我的代码做错了什么,因为我现在花了两个晚上最好的部分无处可去。

简单的测试用例是......

NativeMethods.GpsDevice gpsDevice = new NativeMethods.GpsDevice();
int result = NativeMethods.GPSGetDeviceState(ref gpsDevice);

我的互操作定义如下......

private const string GpsApi = @"gpsapi.dll";

private const int GPS_VERSION_1 = 1;
private const int GPS_MAX_SATELLITES = 12;
private const int GPS_MAX_PREFIX_NAME = 16;
private const int GPS_MAX_FRIENDLY_NAME = 64;

[DllImport(GpsApi)]
public static extern int GPSGetDeviceState(ref GpsDevice pGPSDevice);

[StructLayout(LayoutKind.Sequential)]
public class GpsDevice {

public UInt32 dwVersion;

 public UInt32 dwSize;

 public IoctlServiceStatus dwServiceState;

 public IoctlServiceStatus dwDeviceState;

 public FileTime ftLastDataReceived;

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.GPS_MAX_PREFIX_NAME)]
 public string szGPSDriverPrefix;

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.GPS_MAX_PREFIX_NAME)]
 public string szGPSMultiplexPrefix;

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.GPS_MAX_FRIENDLY_NAME)]
 public string szGPSFriendlyName;

 public GpsDevice() {

  this.dwVersion = NativeMethods.GPS_VERSION_1;
  this.dwSize = (UInt32)Marshal.SizeOf(this);

 }

}

[StructLayout(LayoutKind.Sequential)]
public struct FileTime {
 UInt32 dwLowDateTime;
 UInt32 dwHighDateTime;
}

public enum IoctlServiceStatus : uint {

 Off = 0,

 On = 1,

 StartingUp = 2,

 ShuttingDown = 3,

 Unloading = 4,

 Uninitialised = 5,

 Unknown = 0xffffffff

}

我希望我已经包含了所有可能需要的信息;如果没有,请提示我更多。

提前致谢。

2 个答案:

答案 0 :(得分:3)

将GpsDevice定义为struct而不是class,然后使用MArshal类将其编组为非托管代码

请参阅此处有关如何将struct转换为pionter并返回的示例。

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.structuretoptr.aspx

答案 1 :(得分:1)

我将GpsDevice的定义从一个类改为一个结构,它可以工作!

[StructLayout(LayoutKind.Sequential)]
public struct GpsDevice {
...

}

不得不删除构造函数(这实际上是我首先将它编码为类的原因 - 这样我就可以自动初始化dwSize和dwVersion成员了。)

NativeMethods.GpsDevice gpsDevice = new NativeMethods.GpsDevice {
    dwVersion = NativeMethods.GPS_VERSION_1,
    dwSize = (uint)Marshal.SizeOf(typeof(NativeMethods.GpsDevice))
};

result = NativeMethods.GPSGetDeviceState(ref gpsDevice);

真的很遗憾你不能在结构上拥有构造函数!