Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct marshal in C#

I have the following struct in C#

unsafe public struct control
    {
        public int bSetComPort;
        public int iComPortIndex;
        public int iBaudRate;
        public int iManufactoryID;
        public byte btAddressOfCamera;
        public int iCameraParam;
        public byte PresetNum;
        public byte PresetWaitTime;
        public byte Group;
        public byte AutoCruiseStatus;
        public byte Channel;
        public fixed byte Data[64];
    }

And the function i use to convert it to byte array[] is

 static byte[] structtobyte(object obj)
    {
        int len = Marshal.SizeOf(obj);
        byte[] arr = new byte[len];
        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(obj, ptr, true);
        Marshal.Copy(ptr, arr, 0, len);
        Marshal.FreeHGlobal(ptr);
        return arr;
    }

When i compile it gives

Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

What can be the problem? Thanks in advance!

like image 588
Ungureanu vlad Avatar asked Jun 18 '11 22:06

Ungureanu vlad


People also ask

What is marshaling in C#?

Marshalling is the process of transforming types when they need to cross between managed and native code. Marshalling is needed because the types in the managed and unmanaged code are different.

Why do we use struct?

'Struct' keyword is used to create a structure. A structure can contain variables, methods, static constructor, parameterized constructor, operators, indexers, events, and property. A structure can not derive/inherit from any structure or class. A structure can implement any number of interfaces.

Why is struct used in C#?

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.

What is struct in c3?

A structure type (or struct type) is a value type that can encapsulate data and related functionality. You use the struct keyword to define a structure type: C# Copy.


1 Answers

SizeOf doesn't work on arrays. Use array.Length * Marshal.SizeOf(elementType) instead.

like image 97
Downvoter Avatar answered Oct 13 '22 11:10

Downvoter