c# Marshal structure equivalent of java

1.1k views Asked by At

I would like to create that object same for java. Is it possible to create it?

How it works : you can find more informaiton how I used it.

using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Common.Models;
using System.Text;

namespace Common.Utilities.Helpers
{
    public partial class CommareaHelper
    {
        public static T StringToObject<T>(string buffer)
        {
            IntPtr pBuf = IntPtr.Zero;

            try
            {
                pBuf = Marshal.StringToBSTR(buffer);
                return (T)Marshal.PtrToStructure(pBuf, typeof(T));
            }
            catch
            {
                throw;
            }
            finally
            {
                pBuf = IntPtr.Zero;
            }
        }

        public static string ObjectToString(Object conversionObject)
        {
            int size = 0;
            IntPtr pBuf = IntPtr.Zero;

            try
            {
                size = Marshal.SizeOf(conversionObject);
                pBuf = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(conversionObject, pBuf, false);
                return Marshal.PtrToStringAuto(pBuf, size).Substring(0, size/2);
            }
            catch
            {
                throw;
            }
            finally
            {
                Marshal.FreeHGlobal(pBuf);
            }
        }
    }
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class Comarea
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)]
    private string status;
    public string Status
    {
        get
        {
            return new string(status).Trim();
        }

        set
        {
            status = value.ToFixedCharArray(1, true);
        }
    }

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
    private string operationName;
    public string OperationName
    {
        get
        {
            return new string(operationName).Trim();
        }

        set
        {
            operationName = value.ToFixedCharArray(5, true);
        }
    }
}

I can fill any object using single line of string and opposite of that operation

string commareaStr = "0TR231";
Commarea commarea = CommareaHelper.StringToObject<Commarea>(commareaStr);
0

There are 0 answers