[英]Passing a managed (C#) string[] array to a COM DLL
Setup: 设定:
I have a COM DLL that calls a method inside a managed C# DLL. 我有一个COM DLL,可在托管C#DLL中调用方法。 This function returns a C# string[] array, which is marshaled to a SAFEARRAY. 该函数返回一个C#string []数组,该数组被封送到SAFEARRAY。
Problem: 问题:
When I try to access the strings within the safearray I only get the first char of the string. 当我尝试访问safearray中的字符串时,我只会得到字符串的第一个字符。 What am I doing wrong? 我究竟做错了什么?
The code: 编码:
// Pointer to the managed interface
DatabasePtr pODB(__uuidof(DBClass));
// Get the string[] array from the managed method
SAFEARRAY* safearray = pODB->GetStringArray();
HRESULT hresult;
long ubound;
long lbound;
hresult = SafeArrayGetUBound(safearray, 1, &ubound);
hresult = SafeArrayGetLBound(safearray, 1, &lbound);
long index;
BSTR fromarray;
for (; lbound <= ubound; lbound++)
{
index = lbound;
hresult = SafeArrayGetElement(safearray, &index, (void*)&fromarray);
char buffer[512];
sprintf_s(buffer,"%s",fromarray);
MessageBox(0, (LPCSTR)buffer, "...", 0);
}
Thanks for your help, 谢谢你的帮助,
-Sean! -Sean!
The BSTR is an unicode string, so you must use an wchar_t
buffer and the wsprintf_s
. BSTR是一个unicode字符串,因此您必须使用wchar_t
缓冲区和wsprintf_s
。 Right now u print the ANSI part of the first unicode character then stop on the \\0. 现在,您打印第一个Unicode字符的ANSI部分,然后停在\\ 0上。 And please, please, don't stack overflow like that (sic!). 而且请,请不要那样堆叠堆栈(原文如此!)。 Use the safe _vsnwprintf_s_l
and its family, your code is a hacker's delight as it is right now and u'll be pwned. 使用安全的_vsnwprintf_s_l
及其家族,您的代码很容易受到黑客的欢迎,因为现在您可以将其伪装。 See http://msdn.microsoft.com/en-us/library/d3xd30zz(VS.80).aspx 参见http://msdn.microsoft.com/zh-cn/library/d3xd30zz(VS.80).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.