【问题标题】:Returning a byte array from a C dll to C#将字节数组从 C dll 返回到 C#
【发布时间】:2016-11-07 20:43:26
【问题描述】:

我正在尝试从我的 C# 程序中用 C 语言编写的 DLL 获取字节数组。 DLL 用于与 National Instruments USB-8451 通信。我尝试使用的函数将指向数组的指针作为输出参数返回。我在网上找到的大多数此类问题的问题/答案都有返回指向数组的指针的函数(不使用参数)。

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,所以我可以看到正确的数据输出和返回。

我做错了什么?我看不到它,这真的很令人沮丧。谢谢。

【问题讨论】:

  • 这纯属猜测,但如果将ReadData 定义为byte [](因为out IntPtr 等于**)会发生什么?

标签: c# c arrays dll dllimport


【解决方案1】:

安德罗,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    
        );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 2018-11-07
    • 2017-06-28
    • 2012-04-22
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多