从c#到c+的互操作传递结构+;
c#代码: 我必须将这个结构发送到C++原生函数中的函数:从c#到c+的互操作传递结构+;,c#,c++,interop,C#,C++,Interop,c#代码: 我必须将这个结构发送到C++原生函数中的函数: [DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U4)] public static extern int AFT_iSetRTSECANWrapper(IntPtr Data); 我准备的缓冲区如下: Message frame = new
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int AFT_iSetRTSECANWrapper(IntPtr Data);
我准备的缓冲区如下:
Message frame = new Message();
frame.MsgId = (uint)MsgId;
frame.DLC = (uint)DLC;
frame.Interval = (uint)Interval;
frame.Data = new byte[64];
for (int i = 0; i < Data.Length; i++)
{
frame.Data[i] = 11;
}
//Transmit message
int rawsize = Marshal.SizeOf(frame);
IntPtr frameBuffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(frame, frameBuffer, false);
AFT_iSetRTSECANWrapper(frameBuffer);
要调用的函数是:
extern "C" __declspec(dllexport) int AFT_iSetRTSECANWrapper(Message *data)
在此之后,我只是尝试使用data->DLC访问消息中的字段,但什么也没有得到。我想不出这里有什么问题。我猜数据没有分配到与结构的其余部分相同的连续部分,因此它不会被传输。试一试
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Message
{
public uint MsgId;
public uint DLC;
public uint Handle;
public uint Interval;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] Data = new byte[64];
};
对于C++位,而不是传输到一个ItPtR,直接传递
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int AFT_iSetRTSECANWrapper([in,out] Message Data);
将您的消息发送为
Message frame = new Message();
frame.MsgId = (uint)MsgId;
frame.DLC = (uint)DLC;
frame.Interval = (uint)Interval;
for (int i = 0; i < Data.Length; i++)
{
frame.Data[i] = 11;
}
//Transmit message
AFT_iSetRTSECANWrapper(frame);
消息框=新消息();
frame.MsgId=(uint)MsgId;
frame.DLC=(uint)DLC;
帧间隔=(uint)间隔;
for(int i=0;i
sizeof(char)==sizeof(byte),所以它应该是“unsigned char Data[8]”。我没有看到任何错误。“我什么都没有”是什么意思?使用调试器查看“数据”,您至少应该看到数组中的0x0b字节值。
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int AFT_iSetRTSECANWrapper([in,out] Message Data);
Message frame = new Message();
frame.MsgId = (uint)MsgId;
frame.DLC = (uint)DLC;
frame.Interval = (uint)Interval;
for (int i = 0; i < Data.Length; i++)
{
frame.Data[i] = 11;
}
//Transmit message
AFT_iSetRTSECANWrapper(frame);