c/c++和.net之间相互调用,代码转换工具:
具体转换代码:
![](https://i-blog.csdnimg.cn/blog_migrate/cdec0645add3fc3c328197dda5c76203.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
static object BytesToStruct(byte
[] bytes, Type strcutType)
{
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0 , buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
catch (Exception ex)
{
Console.Write("BytesToStruct,error{0}\r\n" , ex.ToString());
return null ;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false );
byte[] bytes = new byte [size];
Marshal.Copy(buffer, bytes, 0 , size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
{
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0 , buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
catch (Exception ex)
{
Console.Write("BytesToStruct,error{0}\r\n" , ex.ToString());
return null ;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false );
byte[] bytes = new byte [size];
Marshal.Copy(buffer, bytes, 0 , size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-664731/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-664731/