元帅C结构到C# [英] marshal c struct to c#

查看:153
本文介绍了元帅C结构到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有任何机构可以在C#元帅的C / C ++代码,这部分吗?



  typedef结构
{
字节bCommandCode;
字节bParameterCode;

结构
{
DWORD的dwSize;
LPBYTE lpbBody;
}
的数据;
}
命令,* LPCOMMAND;



非常感谢


解决方案

  // 01。声明'命令'结构
公共结构命令
{
公共字节CommandCode;
公共字节ParameterCode;
公共结构数据
{
公共UINT大小;
公共IntPtr的身体;
}
公共数据送出数据;
}

// 02。创建和放大器;指定的'命令'结构
实例//创建数组身体
字节[] =身体{0x33,0x32,0x34,0X31,的0x30};

//从字节获取的IntPtr [](参考:http://stackoverflow.com/questions/537573/how-to-get-intptr-from-byte-in-c-sharp)
的GCHandle pinnedArray = GCHandle.Alloc(身体,GCHandleType.Pinned);
的IntPtr指针= pinnedArray.AddrOfPinnedObject();

// Create命令例如
VAR命令=新CardReaderLib.Command
{
CommandCode =为0x30,
ParameterCode =为0x30,
送出数据= {
尺寸=(UINT)body.Length,
体=指针
}
};

//做你的东西

如果(pinnedArray.IsAllocated)
pinnedArray.Free();


Does any body can marshal this part of c/c++ code in c# please?

typedef struct
{
    BYTE    bCommandCode;
    BYTE    bParameterCode;

    struct
    {
        DWORD   dwSize;
        LPBYTE  lpbBody;
    }
    Data;
}
COMMAND, *LPCOMMAND;

thanks a lot

解决方案

//01. Declare 'Command' structure
public struct Command
{
    public byte CommandCode;
    public byte ParameterCode;
    public struct Data
    {
        public uint Size;
        public IntPtr Body;
    }
    public Data SendData;
}    

//02. Create & assign an instance of 'Command' structure 
//Create body array
byte[] body = { 0x33, 0x32, 0x34, 0x31, 0x30 };

//Get IntPtr from byte[] (Reference: http://stackoverflow.com/questions/537573/how-to-get-intptr-from-byte-in-c-sharp)
GCHandle pinnedArray = GCHandle.Alloc(body, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();

//Create command instance
var command = new CardReaderLib.Command
                  {
                      CommandCode = 0x30,
                      ParameterCode = 0x30,
                      SendData = {
                          Size = (uint) body.Length, 
                          Body = pointer
                      }
                  };

//do your stuff

if (pinnedArray.IsAllocated)
    pinnedArray.Free();

这篇关于元帅C结构到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆