2010-11-01 87 views
2

我需要使用非托管VC++ dll。非托管dll函数字节*参数在C#中返回

它需要C#包装以下两个功能:

bool ReadData(byte* byteData, byte dataSize); 
bool WriteData(byte* byteData, byte dataSize); 

,如果他们成功,他们都返回true,否则为false。

目前在C#中我有一个类(WRAP)与功能:

[DllImport("kirf.dll", EntryPoint = "ReadData", SetLastError=true)] 
[return: MarshalAs(UnmanagedType.VariantBool)] 
public static extern Boolean ReadData([Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)]out Byte[] bytesData, Byte dataSize); 

[DllImport("kirf.dll", EntryPoint = "WriteRFCard", SetLastError = true)] 
[return: MarshalAs(UnmanagedType.VariantBool)] 
public static extern Boolean WriteRFCard[In]Byte[] bytesData, [In]Byte dataSize); 

我再有

byte[] newData = new byte[17]; 
byte dataSize = 17; 
bool result = WRAP.ReadData(out newData, dataSize); 

这总是给我一个结果=假,newData = null,而没有错误抛出(或者总是回来成功)。

而且

byte[] bytesData = new Byte[] { (byte)0x9B, (byte)0x80, (byte)0x12, (byte)0x38, (byte)0x5E, (byte)0x0A, (byte)0x74, (byte)0x6E, (byte)0xE6, (byte)0xC0, (byte)0x68, (byte)0xCB, (byte)0xD3, (byte)0xE6, (byte)0xAB, (byte)0x9C, (byte)0x00 }; 
byte dataSize = 17; 
bool actual = WRAP.WriteData(bytesData, dataSize); 

任何想法,我可能做错了什么?

编辑

这是怎么了我最终设法它:

 [DllImport("kirf.dll", EntryPoint = "ReadData", SetLastError=true)] 
     [return: MarshalAs(UnmanagedType.VariantBool)] 
     public static extern Boolean ReadData([Out] Byte[] bytesData, Byte dataSize); 

[DllImport("kirf.dll", EntryPoint = "WriteData", SetLastError = true)] 
     [return: MarshalAs(UnmanagedType.VariantBool)] 
     public static extern Boolean WriteData([In] Byte[] bytesData, Byte dataSize); 

和:

Byte[] newData=new byte[17]; 
bool result = KABA_KIRF.ReadData(newData, (Byte)newData.Length); 

bool result = KABA_KIRF.WriteData(data, datasize); 

其中数据是传递给函数的Byte[]参数。

+0

您是否确认函数在非托管代码中工作?一个简单的C线束? – 2010-11-01 09:36:23

回答

1

ReadData是否创建一个新的字节数组?否则,我不认为bytesData应该是out参数。

the PInvoke spec of ReadFile比较:

[DllImport("kernel32.dll", SetLastError = true)] 
static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, 
    uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); 

lpNumberOfBytesRead是一个不折不扣PARAM,因为ReadFile的改变了它的价值。即如果您通过lpNumberOfBytesRead的本地变量,则ReadFile将更改堆栈中的值。另一方面,lpBuffer的值是而不是已更改:在调用后它仍指向相同的字节数组。 [In,Out] - 属性告诉PInvoke如何处理您传递的数组的内容

相关问题