gpt4 book ai didi

c# - C# 中的非托管 dll 函数字节 * 参数返回

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:50 27 4
gpt4 key购买 nike

我需要使用非托管 VC++ dll。

它有以下两个需要 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);

这总是给我一个 result=false,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[] 参数。

最佳答案

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 是一个输出参数,因为 ReadFile 改变了它的值。即,如果您为 lpNumberOfBytesRead 传递局部变量,ReadFile 将更改堆栈上的值。另一方面,lpBuffer 的值没有改变:它在调用后仍然指向同一个字节数组。 [In,Out]-Attributes 告诉 PInvoke 如何处理您传递的数组的内容

关于c# - C# 中的非托管 dll 函数字节 * 参数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com