2016-11-07 60 views
0

我想從我的C#程序中用C編寫的DLL獲取一個字節數組。該DLL用於與NI USB-8451進行通信。我試圖使用的函數將返回指向數組的指針作爲輸出參數。在這種類型的問題中,我在網上找到的大多數問題/答案都有函數返回指向數組的指針(不使用參數)。從C DLL返回一個字節數組到C#

c中的函數具有以下原型。

int32 ni845xI2cWriteRead (
    NiHandle DeviceHandle, 
    NiHandle ConfigurationHandle, 
    uInt32 WriteSize, 
    uInt8 * WriteData, 
    uInt32 NumBytesToRead, 
    uInt32 * ReadSize, 
    uInt8 * ReadData 
    ); 

在C#中,我有以下代碼來訪問該DLL。

[DllImport("NI845x.dll")] 
public static extern Int32 ni845xI2cWriteRead(
     IntPtr DeviceHandle, 
     IntPtr ConfigurationHandle, 
     UInt32 WriteSize, 
     byte[] WriteData, 
     UInt32 NumBytesToRead, 
     out UInt32 ReadSize, 
     out IntPtr ReadData 
     ); 

以下代碼是我用來訪問ni845xI2cWriteRead函數的。

Int32 err = 0; 
IntPtr ptrToRead = IntPtr.Zero; 
err = ni845xI2cWriteRead(DeviceHandle, I2CHandle, WriteSize,WriteData, 
     NumBytesToRead, out ReadSize, out ptrToRead); 
byte[] rd = new byte[ReadSize]; 
Marshal.Copy(ptrToRead, rd,0, (int)ReadSize); 

我遇到的問題是獲取ReadData數組。 ReadSize正確返回。我得到的字節數組似乎是相當隨機的。有時全部爲零,有時會有(不正確的)值,有時會出現訪問衝突錯誤。我知道該命令正確地發送和接收來自USB-8451的數據,因爲我使用的是NI I/O Trace,因此我可以看到正確的數據出來並返回。

我在做什麼錯?我看不到它,這真的令人沮喪。謝謝。

+0

這純粹是一種猜測,但如果將'ReadData'定義爲'byte []'(因爲out IntPtr'等於'**'),會發生什麼? – Andro

回答

1

Andro,you nailed it。謝謝!鬆了一口氣。我以前試過out byte[] ReadData,但沒有奏效,但沒有試過byte[] ReadData。下面是正確的DllImport。

[DllImport("NI845x.dll")] 
    public static extern Int32 ni845xI2cWriteRead(
      IntPtr DeviceHandle, 
      IntPtr ConfigurationHandle, 
      UInt32 WriteSize, 
      byte[] WriteData, 
      UInt32 NumBytesToRead, 
      out UInt32 ReadSize, 
      byte[] ReadData  
     );