简体   繁体   English

从 Win32 RPC 调用返回一个字符串

[英]Return a string from Win32 RPC call

I'm trying to make an RPC call which requests 2 numbers and a string from the RPC server, the IDL looks like this:我正在尝试进行 RPC 调用,该调用从 RPC 服务器请求 2 个数字和一个字符串,IDL 如下所示:

void GetCurrentStatus([in] handle_t hBinding, [out, ref] DWORD *dwRef1, [out, ref] DWORD *dwRef2, UINT *nLength, [out, size_is(, *nLength)] LPWSTR *pszName);

In the server-side call I do this:在服务器端调用中,我这样做:

// name = std::wstring
*pszName = (wchar_t*)midl_user_allocate(name.length()+1 * sizeof(wchar_t));
_tcscpy(*pszName, name.c_str());
*nLength = name.length();

But any attempt to call from the client-side results in nothing returned the error The array bounds are invalid.但是任何从客户端调用的尝试都不会返回错误The array bounds are invalid.

What is the correct way to return a string from an RPC call?从 RPC 调用返回字符串的正确方法是什么?

Thanks, J谢谢,J

If you have a choice in the matter, use BSTR (ie SysAllocString ).如果您对此有选择权,请使用BSTR (即SysAllocString )。 RPC knows all about this data type and how to copy it and find its length. RPC 知道所有关于这种数据类型以及如何复制它并找到它的长度。

Just只是

[out, retval] BSTR* pstrName

is enough, no separate length parameter needed.就足够了,不需要单独的长度参数。

The server is not able to pass string value back to client since it doesn't know how to marshall the string..服务器无法将字符串值传递回客户端,因为它不知道如何编组字符串。

When you use BSTR type, the server knows to the length of the string.当你使用 BSTR 类型时,服务器知道字符串的长度。 BSTR must be preceded by a 4-byte length field and terminated by a single null 2-byte character. BSTR 必须以 4 字节长度字段开头,并以单个 null 2 字节字符终止。

Where you have written:你写的地方:

*nLength = name.length();

I believe you need我相信你需要

*nLength = (name.length() + 1) * sizeof(WCHAR);

In particular, if you have an empty (length zero) string, then returning a size_is(0) array is not legal -- so you must add space for the string-terminating NUL ( L'\0' ).特别是,如果您有一个空(长度为零)字符串,则返回size_is(0)数组是不合法的——因此您必须为字符串终止的 NUL ( L'\0' ) 添加空间。

You also want to supply the size in bytes, where each Unicode character uses two bytes -- therefore you must multiply by the character size.您还想以字节为单位提供大小,其中每个 Unicode 字符使用两个字节 - 因此您必须乘以字符大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM