A
A
Alexander Borisovich2014-05-12 15:17:41
C++ / C#
Alexander Borisovich, 2014-05-12 15:17:41

C# - how to convert a string to utf16 and do marshaling?

string ZPLString ="Строка";   
IntPtr pBytes;
pBytes = Marshal.StringToCoTaskMemAnsi(ZPLString );

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
chydaya, 2014-05-12
@chydaya

for example, write a structure with our string

struct StructWithStr
{
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = SIZE_CONST)]
  public string OurStr; 
}

fill it with the desired string
write a helper to save the structure to a pointer
public static class UnMemory<T> where T : struct
{
    public static void SaveInMem(T memoryObject, ref IntPtr ptr)
    {
        if (default(T).Equals(memoryObject))
        {
            // объявляем указатель на кусок памяти
            ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(T)));
            return;
        }
        if (ptr == IntPtr.Zero)
        {
            // объявляем указатель на кусок памяти
            ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(T)));
            // записываем в память данные структуры
            Marshal.StructureToPtr(memoryObject, ptr, false);
  }
        else
        {
            // записываем в память данные структуры
            Marshal.StructureToPtr(memoryObject, ptr, true);
        }
    }
}

pass IntPtr to library

S
Sumor, 2014-05-12
@Sumor

You can use the conversion from string to an array of bytes - the
Encoding.Unicode.GetBytes function for UTF16
Encoding.UTF8.GetBytes for Utf8, etc.
In this case, you must not forget to provide a null character at the end of the string.
If the string will be used for COM - memory allocation through AllocCoTaskMem, if for platform calls - AllocHGlobal.
Well, do not forget to free the memory after use.

var str = "abc\0";
var UTF16data = Encoding.Unicode.GetBytes(str);
var len = UTF16data.Length;
IntPtr pData = Marshal.AllocCoTaskMem(len);
// IntPtr pData = Marshal.AllocHGlobal(len);

… использование pData …

Marshal.Copy(UTF16data, 0, pData, len);
Marshal.FreeCoTaskMem(pData);
// Marshal.FreeHGlobal(pData);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question