我正在Visual Studio 2010中编写C ++ CLI DLL,我期望将字符串返回给Excel VBA:
BSTR __stdcall fnGetData (const double *yr, const double *mon, const char *uid, const char *pwd)
我的功能正常,但字符串在返回Excel时最终会被截断。下面代码中的MessageBoxA调用都显示正确的数据(巨型消息框对话框中的所有8760个字符),但Excel中生成的MsgBox仅显示8760的前998个字符。此函数的整个代码块如下:
BSTR __stdcall fnGetData (const double *yr, const double *mon, const char *uid, const char *pwd) {
//convert Excel ByRef arguments to useable values
string userid(uid);
string passwd(pwd);
int year = *yr;
int month = *mon;
//transform user and pwd to String
System::String ^ UserName = gcnew String(userid.c_str());
System::String ^ PassWord = gcnew String(passwd.c_str());
//call the HTTPWebRequest/Response function on the class
htGetData2 ^ h2 = gcnew htGetData2();
const char* vCharArray = h2->GetStuff(year, month, UserName, PassWord);
//up to this point everything has worked fine
MessageBoxA(0, vCharArray, "hi1 from fnGetData", MB_OK | MB_ICONINFORMATION);
int retValLen = char_traits<char>::length(vCharArray);
//retValLen is 8760
BSTR retVal = SysAllocStringByteLen(vCharArray, retValLen);
int retValLen2 = SysStringLen(retVal);
//retValLen2 is 4380
MessageBoxA(0, (LPCSTR)retVal, "hi2 from fnGetData", MB_OK | MB_ICONINFORMATION);
return retVal;
}
我在做错的是Excel中的BSTR / String不是vCharArray字符串中数据的全部内容?我不使用ATL或MFC,我应该重试吗?
Excel VBA调用是:
Private Declare Function GetData Lib "getpdata.dll" (ByRef year As Double, ByRef month As Double, ByRef uid As Byte, ByRef pwd As Byte) As String
答案 0 :(得分:1)
在excel的VBA中编写一个调用导出的GetData函数的中间函数应该可以解决问题。 类似的东西:
Private Declare Function GetData Lib "getpdata.dll" (ByRef year As Double, ByRef month As Double, ByRef uid As Byte, ByRef pwd As Byte) As String
Function GetDataEx(ByRef year As Double, ByRef month As Double, ByRef uid As Byte, ByRef pwd As Byte) As String
GetDataEx = GetData(year, month, uid, pwd)
End Function
在excel中,使用中间函数代替原始导出函数。
答案 1 :(得分:1)
好的,我一直在使用Excel VBA MsgBox函数来读取DLL编写时从DLL返回的字符串。直到现在我还没有意识到MsgBox有1024个字符的限制,之后就忽略了字符。实际上正在返回完整的字符串,但是我假设MsgBox正在显示它的全长(因为我一直遇到的麻烦都是超过前230个字符的数据)。