Specifying a code page for sorting a PInvoke string using C #

I am calling a DLL using PInvoke. The DLL function returns the string C in code page 437.

Is there a way for the .Net token conversion to convert the string to unicode, or could someone suggest which parameters I should give DllImport () and MarshalAs (), and the conversion function to use to get output to unicode

For reference, this is the DllImport that I am currently using:

[DllImport("name.dll", CharSet=CharSet.Unicode) ]
internal static extern int GetSweepParam(
    int param_num,
    [Out,MarshalAs(UnmanagedType.LPStr)]StringBuilder param_name,
    [Out,MarshalAs(UnmanagedType.LPStr)]StringBuilder param_units,
    double[] values,
    [MarshalAs(UnmanagedType.LPStr)]StringBuilder error_string
);
+3
source share
1 answer

ANSI string marshalling . - , .

[DllImport("name.dll")]
internal static extern int GetSweepParam(
    int param_num,
    [Out]byte[] param_name,
    [Out]byte[] param_units,
    double[] values,
    byte[] error_string
);

static void Test()
{
    Encoding enc = Encoding.GetEncoding(437);
    byte[] param_name = new byte[1000], param_units = new byte[1000];
    GetSweepParam(123, param_name, param_units, new double[0], enc.GetBytes("input only"));
    string name = enc.GetString(param_name, 0, Array.IndexOf(param_name, (byte)0));
    string units = enc.GetString(param_units, 0, Array.IndexOf(param_units, (byte)0));
}

, IntPtr.

static unsafe string PtrToStringAnsiWithEncoding(IntPtr p)
{
    int l = 0;
    byte* bytes = (byte*)p.ToPointer();
    while(bytes[l] != 0) l++;
    char* chars = stackalloc char[l];
    int bytesUsed, charsUsed;
    bool completed;
    Encoding.GetEncoding(437).GetDecoder().Convert(bytes, l, chars, l, true, out bytesUsed, out charsUsed, out completed);
    return new string(chars, 0, charsUsed);
}
+3

Source: https://habr.com/ru/post/1726815/


All Articles