将字节数组从 C dll 返回到 C#
Returning a byte array from a C dll to C#
我正在尝试从我的 C# 程序中用 C 编写的 DLL 获取字节数组。 DLL 用于与 National Instruments USB-8451 通信。我正在尝试使用 returns 指向数组的指针作为输出参数的函数。我在网上找到的大多数 questions/answer 这类问题都有返回数组指针的函数(不使用参数)。
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,所以我可以看到正确的数据输出和返回。
我做错了什么?我看不到它,这真的很令人沮丧。谢谢
安德鲁,。谢谢!松了一口气。我之前曾尝试过 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
);
我正在尝试从我的 C# 程序中用 C 编写的 DLL 获取字节数组。 DLL 用于与 National Instruments USB-8451 通信。我正在尝试使用 returns 指向数组的指针作为输出参数的函数。我在网上找到的大多数 questions/answer 这类问题都有返回数组指针的函数(不使用参数)。
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,所以我可以看到正确的数据输出和返回。
我做错了什么?我看不到它,这真的很令人沮丧。谢谢
安德鲁,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
);