Click here to Skip to main content
14,427,846 members
Rate this:
Please Sign up or sign in to vote.
See more:
hi ,

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

any body send the document of examples

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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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).
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

Another article related to the question,

Mastering structs in C#/[^]

:)
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

thanks for your reply i have some doubts where to ask


thanks
Naga
   
Rate this:
Please Sign up or sign in to vote.

Solution 5

MSDN ARTICLE[^]Gives you a clear Idea about Marshaling and Unmarshaling.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100