gpt4 book ai didi

c# - 从原生 C++ 到 C# 的回调 byte[]

转载 作者:搜寻专家 更新时间:2023-10-31 01:03:16 24 4
gpt4 key购买 nike

我有一个 c++ native dll(不是 CLR),它具有对 c# 应用程序的回调。除以下情况外,所有回调均有效:

C++:

typedef int (__stdcall *TransmitBinaryMessageCallback)(GUID connectionID, byte data[], int data_size);

调用:

GUID ClientID = { 0x12345678, 0xabcd, 0xef12, { 0xfe, 0xdc, 0xa9, 0x87, 0x65, 0x43, 0x21, 0x11 } };
byte arrayB[10] = {0x2,0x4,0x6,0x8,0xaa,0xbb,0xcc,0xdd,0xee,0xff};
transmitBINMessage(ClientID,arrayB,10);

C#

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int TransmitBinaryMessageCallback(Guid ClientID,byte [] data,int data_size

public static int FuncTransmitBinaryMessageCallback(Guid ClientID, byte[] data, int data_size)
{
try
{
System.Windows.Forms.MessageBox.Show("transmitBinaryMessageCallback: clientID=" + ClientID.ToString() + Environment.NewLine +
"data=" + data.ToString() + Environment.NewLine +
"data_size=" + data_size.ToString());
}
catch
{
return -1;
}
return 1;
}

我只得到第一个字节=> 0x2

我也试过:

char[] arrayBytes = new char[data_size];
BinaryReader reader = new BinaryReader(new MemoryStream(data));
int i = reader.Read(arrayBytes, 0, data_size);

我 = 0 :(

我错过了什么?

I could change in c++ from byte [] to char* and in C# to string -> this work. BUT i want byte array, why it not work?!

最佳答案

编码器不知道字节数组有多长。它没有办法编码它。我会将 data 声明为 IntPtr,然后使用 Marshal.Copy 从非托管内存复制到字节数组。

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int TransmitBinaryMessageCallback(Guid ClientID, IntPtr dataPtr, int data_size);

然后在回调实现里面

byte[] data = new byte[data_size];
Marshal.Copy(dataPtr, data, 0, data_size);

关于c# - 从原生 C++ 到 C# 的回调 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25572221/

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