Click here to Skip to main content
15,891,833 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi ,

i am new to csharp how to marshal the c structures into c sharp.

any body send the document of examples

C#
public byte[] StructureToByte(object objStructure, int iLength)
        {
            byte[] destination = new byte[iLength];
            IntPtr ptr = Marshal.AllocHGlobal(iLength);
            Marshal.StructureToPtr(objStructure, ptr, true);
            Marshal.Copy(ptr, destination, 0, iLength);
            Marshal.FreeHGlobal(ptr);
            return destination;
        }


what is the purpose of StructureToByte convertion.

have a nice day.

regards
Naga
Posted

There are lots of articles and tutorials on internet about marshaling. for example this one:
http://www.c-sharpcorner.com/UploadFile/GemingLeader/617/[^]

Marshaling is the process of translating managed memory into native memory (or native memory to managed memory) so that .NET applications can exchange data with native applications.

Your function StructureToByte converts a managed structure into a byte array. This byte array can then be sent to a native DLL for example. You can send the managed structure directly to the native DLL because it resides in managed memory (not accessible from native code).
 
Share this answer
 
hi thanks for your reply.

i have need to write the structure and i wrote the sample , if it is write or wrong please check it.

Requirement:

Messagetype long(4)
MessageTag Long(4)
Tcode Char(7)
Password unsignedcahr(16)
Reserved char

Solution of Structure:

[StructLayout(LayoutKind.Sequential, Pack = 1 )]
public struct sample
{

[MarshalAs(UnmanagedType.U4)]
public uint MessageType;
[MarshalAs(UnmanagedType.U4)]
public uint MessageTag;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 7)]
public string Code;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string sPassword;
[MarshalAs(UnmanagedType.I1)]
public char cReserved;
}

My doubt is it correct or instead of
[MarshalAs(UnmanagedType.U4)]
public uint MessageType;
[MarshalAs(UnmanagedType.U4)]
public ulong MessageType;


please send your feed back .

thanks
naga
 
Share this answer
 
Another article related to the question,

Mastering structs in C#/[^]

:)
 
Share this answer
 
thanks for your reply i have some doubts where to ask


thanks
Naga
 
Share this answer
 
MSDN ARTICLE[^]Gives you a clear Idea about Marshaling and Unmarshaling.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900