I'm trying to make an RPC call which requests 2 numbers and a string from the RPC server, the IDL looks like this:
void GetCurrentStatus([in] handle_t hBin开发者_StackOverflow社区ding, [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.
What is the correct way to return a string from an RPC call?
Thanks, J
If you have a choice in the matter, use BSTR
(i.e. SysAllocString
). RPC knows all about this data type and how to copy it and find its length.
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 must be preceded by a 4-byte length field and terminated by a single null 2-byte character.
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'
).
You also want to supply the size in bytes, where each Unicode character uses two bytes -- therefore you must multiply by the character size.
精彩评论