有没有任何机构可以在c#中编制这部分c/C++代码?元帅c结构到c#
typedef struct
{
BYTE bCommandCode;
BYTE bParameterCode;
struct
{
DWORD dwSize;
LPBYTE lpbBody;
}
Data;
}
COMMAND, *LPCOMMAND;
非常感谢
有没有任何机构可以在c#中编制这部分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
属性在这里和那里,以确保它实际上是将它们编为适当的类型。如果你想,然后从内存中读取例如这个结构,你可以这样做:
var bytes = ReadBytes(address, Marshal.SizeOf(typeof(SomeStruct)), isRelative);
fixed (byte* b = bytes)
return (T) Marshal.PtrToStructure(new IntPtr(b), typeof (SomeStruct));
我假设你想从内存中读取你的结构,并封成一个管理结构,否则你不会告发”根本不需要Marshal
。另外,请确保已启用/unsafe
编译上述代码。
不,lpbBody是一个指向字节数组的指针。 –
然后只需将lpBody更改为'byte []',你应该没问题。尽管指定字节数组的长度,否则东西可能会南下。 – aevitas
struct Data {}是一个相当奇怪的声明。在问题“数据”是内部结构的名称 –
//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();
你到目前为止尝试了什么? – user1908061