c/c++和.net之间相互调用,代码转换工具:

1.http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2008_01.exe

2.c++/c#互转工具

 

具体转换代码:

代码
 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);
            }

        }   

 

 

 

相关文章: