程序通过命名管道在C#和C++之间互发结构体,2边定义的结构体顺序和大小都一样,但是还原结构体的时候总是对不上,请大侠们帮找下问题所在,谢谢...
C++定义结构体为:typedef struct __CoData
{
int Events ;
int Ping ;
int Type;
bool xxxxx;
bool yyyyy ;
int Num ;
}CoData;
C#定义的结构体:
[Serializable]
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct stCommunicationData
{
public int Events;
public int Ping;
public int Type;
public bool xxxxx;
public bool yyyyy;
public int Num;
}
C#接收到结构体之后的转换:
public static Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
if (size > bytes.Length)
{
return null;
}
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
网上挺多这方面例子的,但是我始终转换不对.....
起初怀疑是管道通信出了问题,将结构体去掉后,只在C++和C#间发0123456789,能够正常接收,排除了管道的问题。
加上结构体,我用C#做了一个发送一个接收,一切正常。
对C++不熟,实在是不知道上面哪个地方出了问题
C++定义结构体为:typedef struct __CoData
{
int Events ;
int Ping ;
int Type;
bool xxxxx;
bool yyyyy ;
int Num ;
}CoData;
C#定义的结构体:
[Serializable]
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct stCommunicationData
{
public int Events;
public int Ping;
public int Type;
public bool xxxxx;
public bool yyyyy;
public int Num;
}
C#接收到结构体之后的转换:
public static Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
if (size > bytes.Length)
{
return null;
}
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
网上挺多这方面例子的,但是我始终转换不对.....
起初怀疑是管道通信出了问题,将结构体去掉后,只在C++和C#间发0123456789,能够正常接收,排除了管道的问题。
加上结构体,我用C#做了一个发送一个接收,一切正常。
对C++不熟,实在是不知道上面哪个地方出了问题
解决方案 »
- c#如何从串口获得扫描枪数据
- C#下怎么用Nodes.Item?
- WINFORM 部署时,如何修改配置文件中的数据库连接字符串
- 求教个正则表达式
- 如果一个class里面只有一个private成员,客户怎么访问?(.net)
- void 与 bool 之间的转换
- 怎么样把\u6240\u6709\u6587\u4ef6这样的字串转为中文呀?
- 在线等待:如何把DataGrid中数据导出到Excel中(不是通过DataTable),谢谢!
- 求助,win8下如何获取和修改IP及DNS
- 微信获取唯一标识疑问,请高手们帮忙?
- C#如何实现电台的功能
- C# 一个监听 同时判断多个客户端发来的信息,有时候没有监听到!
而,而如果在vc++中返回的是bool(仅是1个字节),当然会出错!
解决的两种办法:
1. VC中返回BOOL(或是直接返回int);
2. 在c#中加上关键字: MarshalAs(UnmanagedType.I1);
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct CoData
{
public int Events;
public int Ping;
public int Type;
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.I1)]
public bool xxxxx;
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.I1)]
public bool yyyyy;
public int Num;
}