Empacotamento de string C # e LocalAlloc
Eu tenho um retorno de chamada COM de uma DLL não gerenciada que eu preciso usar em C #. A DLL não gerenciada espera que o receptor aloque memória usandoLocalAlloc
(que o chamador iráLocalFree
), preencha-o comWSTR
E definirvalue
echars
para o ponteiro WSTR e o comprimento da string, respectivamente.
Fragmento de código que estou tentando converter em c #:
STDMETHODIMP CMyImpl::GetString(LPCSTR field, LPWSTR* value, int* chars) {
CStringW ret;
if (!strcmp(field, "matrix")) {
ret = L"None";
if (...)
ret.Append(L"001");
else if (...)
ret.Append(L"002");
else
ret.Append(L"003");
}
if (!ret.IsEmpty()) {
int len = ret.GetLength();
size_t sz = (len + 1) * sizeof(WCHAR);
LPWSTR buf = (LPWSTR)LocalAlloc(LPTR, sz);
if (!buf) {
return E_OUTOFMEMORY;
}
wcscpy_s(buf, len + 1, ret);
*chars = len;
*value = buf;
return S_OK;
}
return E_INVALIDARG;
}
Qual seria o código C # equivalente?
EDIT: Interface COM:
[id(2)] HRESULT GetString([in] LPCSTR field, [out] LPWSTR* value, [out] int* chars);