2013-06-29 131 views
0

有沒有任何機構可以在c#中編制這部分c/C++代碼?元帥c結構到c#

typedef struct 
{ 
    BYTE bCommandCode; 
    BYTE bParameterCode; 

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

非常感謝

+0

你到目前爲止嘗試了什麼? – user1908061

回答

0

首先,聲明上述結構的管理結構 - 是這樣的:

[StructLayout(LayoutKind.Sequential)] 
    struct SomeStruct 
    { 
     byte bCommandCode; 
     byte bParameterCode; 

     SomeOtherStruct otherStruct; 

     Data Data; 
    } 

    struct SomeOtherStruct 
    { 
     uint dwSize; 
     byte lpBody; 
    } 

    struct Data 
    { 
    } 

雖然你可能不得不使用MarshalAs屬性在這裏和那裏,以確保它實際上是將它們編爲適當的類型。如果你想,然後從內存中讀取例如這個結構,你可以這樣做:

 var bytes = ReadBytes(address, Marshal.SizeOf(typeof(SomeStruct)), isRelative); 

     fixed (byte* b = bytes) 
      return (T) Marshal.PtrToStructure(new IntPtr(b), typeof (SomeStruct)); 

我假設你想從內存中讀取你的結構,並封成一個管理結構,否則你不會告發」根本不需要Marshal。另外,請確保已啓用/unsafe編譯上述代碼。

+0

不,lpbBody是一個指向字節數組的指針。 –

+0

然後只需將lpBody更改爲'byte []',你應該沒問題。儘管指定字節數組的長度,否則東西可能會南下。 – aevitas

+0

struct Data {}是一個相當奇怪的聲明。在問題「數據」是內部結構的名稱 –

0
//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();