开发者

Call StrFormatByteSize64 function from within C#

how can I call the StrFormatByteSize64 function from the Win API from within C#? I'm trying the following code, but without success:

[DllImport("shlwapi.dll")]
static extern void StrFormatByteSize64(ulong qdw, char[] pszBuf, uint cchBuf);

char[] temp = new char[128];
ulong size = 2000;开发者_如何学编程
StrFormatByteSize64(size, temp, 128);
Console.WriteLine(temp);

The function's documentation can be found here: http://msdn.microsoft.com/en-us/library/bb759971%28VS.85%29.aspx

Thank you!


This works, although it may not be the cleanest way:

using System;
using System.Runtime.InteropServices;
using System.Text;

public class Test
{    
    [DllImport("shlwapi.dll")]
    static extern void StrFormatByteSize64(ulong qdw, StringBuilder builder,
                                           uint cchBuf);

    static void Main()
    {
        ulong size = 2000;
        StringBuilder builder = new StringBuilder(128);
        StrFormatByteSize64(size, builder, builder.Capacity);
        Console.WriteLine(builder);
    }
}

I'm afraid I don't know much about interop - it could be that you don't need to specify the initial capacity of the StringBuilder, for example. I'm not sure :( Anyway, it should provide you with a starting point for further investigation.


Try adding [Out] before char[].


Edit:

I can't believe I didn't notice this sooner, but another problem is that your function is not void! It returns a pointer. You might want to fix that if you want it to work. :)

[DllImport("shlwapi.dll")]
static extern IntPtr StrFormatByteSize64(long qdw, [In] StringBuilder pszBuf,
                                         uint cchBuf);

//...
ulong num = 10000000;
var sb = new StringBuilder(1024);
if (StrFormatByteSize64(num, sb, (uint)sb.Capacity) != IntPtr.Zero)
{
    //Conversion successful... do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜