VBA/Excel, and C++ DLL, specifically problems with strings

旧街凉风 提交于 2019-12-11 05:49:02

问题


I am working on a project for serial communications between Excel and an Arduino. The following is what I have in VBA for the reading of data from the Arduino which is where my problem lies.

Private Declare Function readFromSerialPort Lib "C:PathToDll.dll"(ByRef Buffer As String) As String

And in a looping function within my VBA I have the following which sets a cell value to a string which is my buffer.

BigData.Range("Buf").Value = "B                                            "

Another cell called dataWindow takes in Buf as an argument so it updates when this is called.

=readFromSerialPort(Buf)

And here is the C++ code on the other end in the DLL.

DLL_EXPORT BSTR WINAPI readFromSerialPort(LPBSTR bufferTemp) {
char errorMsg[] = "read failed";
char mbstring[MAX_STRING_SIZE];
BSTR wcstring = *bufferTemp;
int sLen = wcstombs(mbstring,wcstring,MAX_STRING_SIZE);

char charString[MAX_STRING_SIZE];
DWORD dwBytesRead = 0;

if (hSerial == INVALID_HANDLE_VALUE) {
    ErrorExit("ReadFile (port not open)");
    int wLen2 = mbstowcs(*bufferTemp,errorMsg,strlen(errorMsg));
    return *bufferTemp;
}

if(!ReadFile(hSerial, charString, sLen, &dwBytesRead, NULL)) {
    ErrorExit("ReadFile");
    int wLen2 = mbstowcs(*bufferTemp,errorMsg,strlen(errorMsg));
    return *bufferTemp;
}

int wLen2 = mbstowcs(*bufferTemp,charString,sLen);
return *bufferTemp;
}

The issue is that this works when called from a cell but not when I change it to declaring a string in VBA and calling the read from there.


回答1:


GSerg has solved this issue. I had not understood that VBA automatically converts when passing as String, so that in the DLL I am not dealing with BSTRs but with ASCII char* or LPSTRs. Also that due to a bug in excel, calling functions from within a cell does not do this conversion.



来源:https://stackoverflow.com/questions/44396538/vba-excel-and-c-dll-specifically-problems-with-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!