问题描述
我有一个从非托管的DLL,我需要在C#中使用COM回调。
中的非托管的DLL预期被叫方使用 LocalAlloc
(其中主叫方将 LocalFree
),填充分配内存它与 WSTR
并设置值
和字符
来的WSTR 。指针和分别字符串长度
I have a COM callback from an unmanaged DLL that I need to use in C#.The unmanaged DLL expects the callee to allocate memory using LocalAlloc
(which the caller will LocalFree
), populate it with WSTR
and set value
and chars
to the WSTR pointer and string length respectively.
代码段,我想转换到C#:
Code snippet I'm trying to convert to 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;
}
将相当于C#代码是什么?
What would the equivalent C# code be?
编辑:COM接口:
[ID(2)] HRESULT GetString的([IN] LPCSTR领域,[出] LPWSTR *值,[出]为int *字符);
推荐答案
直观的方式将进口功能,转换成字符串使用的,然后将其复制到与的。
Straightforward way would be to import LocalAlloc function, convert the string to bytes using UnicodeEncoding.GetBytes and copy them to allocated memory with Marshall.Copy.
这篇关于C#字符串编组LocalAlloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!