使用WinAPI函数,它使用C样式字符串作为OUT参数 [英] Working with WinAPI functions which use C style strings as OUT parameters

查看:138
本文介绍了使用WinAPI函数,它使用C样式字符串作为OUT参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个WinAPI函数,通过C风格字符串OUT参数返回它的结果例如:

  int WINAPI GetWindowTextW $ b _In_ HWND hWnd,
_Out_ LPTSTR lpString,
_In_ int nMaxCount
);

有没有更好的方法使用该函数比下面我做的更好?

  HWND句柄; //假设它初始化为包含一个真实的窗口句柄
std :: wstring title;
wchar_t buffer [512];
GetWindowTextW(handle,buffer,sizeof(buffer));
title = buffer;

上述代码可以工作,但我遇到以下问题:


  1. 缓冲区大小是完全任意的,因为我无法知道函数可能返回的字符串的长度。这个感觉对我错了 - 我一直试图避免在我的代码中的幻数。


  2. 如果函数返回一个大于缓冲区的字符串,它会被截断 - 这是坏的!


  3. 每当函数返回一个小于缓冲区的字符串,我会浪费内存。这不像(2)那样糟糕,但是对于在实际中可能只需要几个字节的东西,放置一大块内存(例如上面的例子中为1024字节)的想法并不感激。

    解决方案 div>

    使用不同大小的临时缓冲区多次调用函数。从一个缓冲区开始,例如,8.加倍缓冲区大小并再次调用它。重复,直到它返回与上次相同的计数。然后你可以分配确切的大小缓冲区,并复制你有那里。有很多类似行为的Win32函数。



    你可以使用 GetWindowTextLength()如果有种族条件(你可能最终会有一个截断的文本,因为他们)。


    Given a WinAPI function which returns it's result via a C style string OUT parameter e.g.:

    int WINAPI GetWindowTextW(
       _In_   HWND hWnd,
       _Out_  LPTSTR lpString,
       _In_   int nMaxCount
    );
    

    Is there a better way of using the function than what I'm doing below?

    HWND handle; // Assume this is initialised to contain a real window handle
    std::wstring title;
    wchar_t buffer[512];
    GetWindowTextW(handle, buffer, sizeof(buffer));
    title = buffer;
    

    The above code works, but I have the following issues with it:

    1. The buffer size is completely arbitrary since I have no way to know the length of the string that the function might return. This "feels" wrong to me - I have always tried to avoid magic numbers in my code.

    2. If the function returns a string which is larger than the buffer, it will get truncated - this is bad!

    3. Whenever the function returns a string which is smaller than the buffer, I will be wasting memory. This is not as bad as (2), but I'm not thrilled about the idea of setting aside large chunks of memory (e.g. 1024 bytes in my example above) for something that might only need a few bytes in practice.

    Are there any other alternatives?

    解决方案

    Call the function multiple times with temporary buffers of different sizes. Begin with a buffer of, say, 8. Double the buffer size and call it again. Repeat until it returns the same count as the last time. Then you can allocate the exact size buffer and copy what you've got there. There are a number of Win32 functions with similar behavior.

    You may use GetWindowTextLength(), but it probably won't help much if there are race conditions (you may end up with a truncated text because of them).

    这篇关于使用WinAPI函数,它使用C样式字符串作为OUT参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆