I want to write a plugin for a program. The program can only use C/C++ *.dll libraries. I want to write my plugin in C# though, so I thought I could just call my C# functions from the C++ dll through COM. This works fine but now I need to access a struct provided by the original program. In C++ this struct looks like this:
struct asdf{
char mc[64];
double md[10];
unsigned char muc[5];
unsigned char muc0 : 1;
unsigned char muc1 : 1;
unsigned char muc2 : 6;
unsigned char muc3;
another_struct st;
};
To be able to pass that struct to C# as a parameter I tried to built exactly the same struct in C#. I tried the following, but it gives me an access violation:
struct asdf{
char[] mc;
double[] md;
byte[] muc;
byte muc0;
byte muc1;
byte muc2;
byte muc3;
another_struct st;
};
What do I have to change?
If you want the arrays inline, you need to use fixed-size buffers. I'm assuming that the C char is a byte. The code to handle muc0, muc1, etc. will require some custom properties. You treat the entire thing like a byte.
struct asdf
{
public fixed byte mc[64];
public fixed double md[10];
public fixed byte muc[5];
private byte mucbyte;
// These properties extract muc0, muc1, and muc2
public byte muc0 { get { return (byte)(mucbyte & 0x01); } }
public byte muc1 { get { return (byte)((mucbyte >> 1) & 1); } }
public byte muc2 { get { return (byte)((mucbyte >> 2) & 0x3f); } }
public byte muc3;
public another_struct st;
};
I would change it slightly, use a string and make sure you init your arrays to the same size used in the C++ code when you use the struct in your program.
struct asdf{
string mc;
double[] md;
byte[] muc;
byte muc0;
byte muc1;
byte muc2;
byte muc3;
};
Related
I have to Develop a Service (C#) which read data from Network Device via TCP Socket and convert this is C# structure.
I am basing on existing, old Delphi application which is doing all this stuff and I have to migrate logic in C#.
EDITED:
I got a snapshot from C-Source of original data-structure:
struct _RequestMsgStruct
{
UCHAR request_ver; //In DELPHI it is represented as Byte
USHORT mac_addr[3]; /* MAC Address */
UINT product_type; //In DELPHI - Cardinal
UCHAR supply_type; //In DELPHI - Byte
short reserved0; //In DELPHI - SmallInt
UCHAR oper_ver[4]; //In DELPHI - CARDINAL !!!
USHORT brd_id; //In DELPHI - WORD
unsigned short exp_id1; //In DELPHI - WORD
//In DELPHI - string[15]; //Array [0..15] of char;
UCHAR serial_no[16]; /* Serial Number. 16th char have to be NULL */
UCHAR _name[32]; /* Name */ //Length of payload may vary //In DELPHI - string[31]
float data_avg; //In DELPHI - Single
ULONG key[5]; //In DELPHI - array [0..19] of Byte
}__attribute__ ((packed));
There is Delphi Packed record with over 200 fields of different types... it look approximately like:
TREC_DATA = packed record
ID : Byte;
MAC_ADDRESS : array [0..5] of Byte;
fieldCard : cardinal;
fieldSI : SmallInt;
fieldW : WORD;
SERIAL_NUMBER : string[15]; //Array [0..15] of char;
fieldSingle : Single;
fieldArrOfB : array [0..19] of Byte;
end;
To move byte array to structure in Delphi there is next code:
Move(inBytesArr[StartIdx], DelphiStruct, aMsgSize)
To convert string files (e.g. SERIAL_NUMBER) there is also such code:
var
pc: Pchar;
...
pc := #inBytesArr[StartIdx + SerialN_Pos_Idx];
DelphiStruct.SERIAL_NUMBER := pc;
I having deal with such conversion for first time and I don't know from where to start:
How to convert this structure to c#?
-- Should I use LayoutKind.Sequential or LayoutKind.Explicit, with or wiyhout [FieldOffset(N)] attribute?
-- How I have to declare array of bytes in target c# structure: as fixed buffer or using [MarshalAs(UnmanagedType.ByValArray...)] attribute?
Which is better way to marshal input bytes array to final C# structure: using Marshal.PtrToStructure or GCHandle.Alloc(bytes, GCHandleType.Pinned) + AddrOfPinnedObject?
Please help me, at least, to get start point in understating from where i need to start.
By default, Delphi's packed records align fields by single byte boundary.
Hence, you should use something like this:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TREC_DATA
{
public byte ID;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] MAC_ADDRESS;
public uint fieldCard;
public short fieldSI;
public ushort fieldW;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] SERIAL_NUMBER;
public float fieldSingle;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] fieldArrOfB;
}
The only thing I'm not sure (and can't test now without Deplhi), is a SERIAL_NUMBER field.
After your update: in original, SERIAL_NUMBER is just a null-terminated string.
Simple question, but I can't find a straight answer: I want to have a char array of 128 bytes in my C structure. I am running this under 64bit Windows. I want to marshal this over to c#, using the following:
The C code:
typedef struct s_parameterStuct
{
int count;
char name[ 128 ];
} parameterStruct;
And the c# code:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class parameterStuct
{
public int count;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public char[] name;
}
Since a char is 2 bytes in c#, should the SizeConst be 128 or 256. Both seem to work fine, but I know only one of them is correct.
The size would be 64, since 64 2-byte quantities have the same size as 128 1-byte ones.
I'd use a byte array for marshaling because otherwise you'll have to put up with splitting values in order to get the C chars (which are single bytes).
If you want to marshal to a C# char array (not sure why you would want to) then the size would be set to 64 on the C# end.
However, you should be marshaling to a byte array (size 128) and then converting the byte array to a .net string (assuming you want a string) using the appropriate Text.Encoding call.
I am currently developing an application to work with WAV files. I want to be able to display the information in the struct with its native type, but C# thinks of char as a 16 bit value.
The four bytes ChunkID0...3 are supposed to contain 'R' 'I' 'F' 'F'
[StructLayout(LayoutKind.Explicit, Size = 12, Pack = 1)]
public unsafe struct RiffDescriptor
{
[FieldOffset(0)]
public byte ChunkID_0;
[FieldOffset(1)]
public byte ChunkID_1;
...
}
I want the debugger to show the ChunkID as 'R' instead of 122.
Any thoughts?
public class RiffDescriptor
{
public RiffDescriptor(BinaryReader b)
{
// Read the ChunkID - Should be RIFF
ChunkID = b.ReadBytes(4);
// Read the ChunkSize
ChunkSize = b.ReadUInt32();
// Read the Format - Should be WAVE
Format = b.ReadBytes(4);
}
[DebuggerDisplay("ChunkID = {System.Text.Encoding.Default.GetString(ChunkID)}")]
public byte[] ChunkID;
public UInt32 ChunkSize;
[DebuggerDisplay("Format = {System.Text.Encoding.Default.GetString(Format)}")]
public byte[] Format;
}
I need to create a binary blob of empty data to PInvoke a native C++ dll that needs a unsigned char* of nulls.
The native C++ program is expecting a structure of data, and there's a nulled area of bytes in the middle, but in C# I can't just make a struct with an initialized byte[] in the middle.
My struct in C++ looks like this
struct myStruct
{
byte command;
byte returncode;
void* Source (a pointer to a string, rather a null term char*)
void* Destination (same thing)
byte filler [99]
byte options;
}
I've already figured that I can take a string and convert it to an array of bytes using myStruct.Source = (void*)Marshal.StringtToGlobalAnsi(source) (correct me if I'm wrong).
But I don't know how to fill out that empty array of bytes in the middle.
This is my C# struct so far.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct Trans_s
{
public byte command;
public byte returnCode;
public void* pSource;
public void* pDest;
public byte* filler;
public byte options;
}
For the array of bytes, you need to mark the field in the C# struct as a byvalarray. The default marshaller uses LPArray if you do not.
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 99)]
public byte[] filler;
You need to allocate the memory for filler when you create an instance of the struct.
No, the C++ code doesn't expect an unsigned char* of nulls. It expects that many padding bytes inside the struct.
The C# fixed keyword might help you here.
his question is about converting between a struct and a byte array. Many solutions are based around GCHandle.Alloc() and Marshal.StructureToPtr(). The problem is these calls generate garbage. For example, under Windows CE 6 R3 about 400 bytes of garbarge is made with a small structure. If the code below could be made to work the solution could be considered cleaner. It appears the sizeof() happens too late in the compile to work.
public struct Data
{
public double a;
public int b;
public double c;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe struct DataWrapper
{
private static readonly int val = sizeof(Data);
[FieldOffset(0)]
public fixed byte Arr[val]; // "fixed" is to embed array instead of ref
[FieldOffset(0)]
public Data; // based on a C++ union
}
You can in fact use the constant value 1 as the size of the fixed array in DataWrapper. There is no bounds checking when accessing an unsafe fixed array nor is there any mechanism to request its length at runtime. The presence of the Data member at offset 0 is enough to ensure that you can actually read and write sizeof(Data) bytes to/from DataWrapper.Arr.
With that said, a more straight forward solution would be to cast a Data* pointer to byte* as follows:
unsafe {
Data d = new Data();
d.a = 125.5;
d.b = 0x7FEEDDEE;
d.c = 130.0;
byte* bytes = (byte*)&d;
for (int i = 0; i < sizeof(Data); i++) {
Console.WriteLine(i + ": " + bytes[i]);
}
}