使用 lxn/win 在 golang 中处理 LPTSTR [英] Handling LPTSTR in golang with lxn/win
问题描述
我有一段代码,它在不返回err
的情况下运行,但它没有完成它的工作,因为它没有返回预期值.这个想法是使用 SHGetSpecialFolderPath
以检索 Windows 目录的路径(例如 C:\Windows
).此 API 调用具有以下签名:
I have this piece of code which runs without returning err
but simply doesn't do its job because it doesn't return the expected value.
The idea is to use SHGetSpecialFolderPath
in order to retrieve the path to the Windows directory (C:\Windows
for example). This api call has the following signature:
BOOL SHGetSpecialFolderPath(
HWND hwndOwner,
_Out_ LPTSTR lpszPath,
_In_ int csidl,
_In_ BOOL fCreate );
我知道它已被弃用,但即使在当前的 Windows 版本上仍然可用.我必须使用这个 API,因为我需要支持早于 Windows 7 的 Windows 版本(我知道这些版本已经过时甚至生命周期结束)
I know it is deprecated, but still available even on current Windows versions. I have to use this API because I need to support Windows versions older than Windows 7 (I know that these are old or even end of life)
这是一段代码:
target := "XXX...XXX" // hard coded string with more than 600 characters
buffer, err := syscall.UTF16PtrFromString(target)
if err != nil {
fmt.Println("conversion of string:", err)
}
result := win.SHGetSpecialFolderPath(0, buffer, win.CSIDL_WINDOWS, false)
if err != nil {
fmt.Println("result of get folder:", err)
}
fmt.Println("folder retrieved ok: ", result)
fmt.Println("folder: ", target)
}
err
均未设置,API 调用返回 true
但字符串未更改:
None of the err
is set, the API call returns true
but the string is unchanged:
folder retrieved ok: true
folder: XXX...XXX
结果在 Windows 10 x64 和运行 Windows XP SP3 的测试 VM 上是相同的(我知道 XP 本质上是不安全的)
The result is the same on Windows 10 x64 and on my testing VM running Windows XP SP3 (I know that XP is inherently unsafe)
我已经看到了如何将 LPTRSTR
与 unsafe
和 uintptr
一起使用的示例 在 SO 和其他网站上,但没有一个在我的 golang 版本上编译(这是 go version go1.10.1 windows/amd64code>,我用
GOARCH=386
)
I have seen examples how to use LPTRSTR
with unsafe
and uintptr
here on SO and other sites but none of them compile on my version of golang (which is go version go1.10.1 windows/amd64
, I compiled with GOARCH=386
)
推荐答案
以逻辑、系统的方式解决问题.
Approach the problem in a logical, systematic fashion.
请仔细阅读有关该功能的 Microsoft 文档.
Carefully read the Microsoft documentation for the function.
仔细阅读函数的 lxn/win
包文档.
Carefully read the lxn/win
package documentation for the function.
import "github.com/lxn/win"
func SHGetSpecialFolderPath(hwndOwner HWND, lpszPath *uint16, csidl CSIDL, fCreate bool) bool
<小时>
现在,使用文档,在 Go 中实现函数调用.Go Unicode 字符串采用 UTF-8 编码.Windows Unicode 字符串采用 UTF-16 编码.
Now, using the documentation, implement the function call in Go. Go Unicode strings are UTF-8 encoded. Windows Unicode strings are UTF-16 encoded.
package main
import (
"fmt"
"syscall"
"github.com/lxn/win"
)
func main() {
buf := make([]uint16, win.MAX_PATH)
rv := win.SHGetSpecialFolderPath(win.HWND(0), &buf[0], win.CSIDL_WINDOWS, false)
fmt.Println(rv)
path := syscall.UTF16ToString(buf)
fmt.Println(path)
}
输出:
true
C:\Windows
这篇关于使用 lxn/win 在 golang 中处理 LPTSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!