[英]marshal c struct to c#
請問有人可以在C#中封送這部分C / C ++代碼嗎?
typedef struct
{
BYTE bCommandCode;
BYTE bParameterCode;
struct
{
DWORD dwSize;
LPBYTE lpbBody;
}
Data;
}
COMMAND, *LPCOMMAND;
非常感謝
首先,將上述結構聲明為托管結構-類似於:
[StructLayout(LayoutKind.Sequential)]
struct SomeStruct
{
byte bCommandCode;
byte bParameterCode;
SomeOtherStruct otherStruct;
Data Data;
}
struct SomeOtherStruct
{
uint dwSize;
byte lpBody;
}
struct Data
{
}
盡管您可能必須在MarshalAs
使用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
編譯以上代碼。
//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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.