Using pinvoke in c# to call sprintf and friends on 64-bit

Posted by bde on Stack Overflow See other posts from Stack Overflow or by bde
Published on 2010-03-19T17:06:19Z Indexed on 2010/03/19 17:11 UTC
Read the original article Hit count: 824

Filed under:
|
|

I am having an interesting problem with using pinvoke in C# to call _snwprintf. It works for integer types, but not for floating point numbers.

This is on 64-bit Windows, it works fine on 32-bit.

My code is below, please keep in mind that this is a contrived example to show the behavior I am seeing.

class Program
{
    [DllImport("msvcrt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    private static extern int _snwprintf([MarshalAs(UnmanagedType.LPWStr)] StringBuilder str, uint length, String format, int p);

    [DllImport("msvcrt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    private static extern int _snwprintf([MarshalAs(UnmanagedType.LPWStr)] StringBuilder str, uint length, String format, double p);

    static void Main(string[] args)
    {
        Double d = 1.0f;
        Int32 i = 1;
        Object o = (object)d;
        StringBuilder str = new StringBuilder();

        _snwprintf(str, 32, "%10.1f", (Double)o);
        Console.WriteLine(str.ToString());

        o = (object)i;
        _snwprintf(str, 32, "%10d", (Int32)o);
        Console.WriteLine(str.ToString());

        Console.ReadKey();
    }
}

The output of this program is

   0.0
     1

It should print 1.0 on the first line and not 0.0, and so far I am stumped.

© Stack Overflow or respective owner

Related posts about c#

Related posts about pinvoke