且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VBA / Excel和C ++ DLL,具体是字符串的问题

更新时间:2023-02-08 14:18:14

GSerg已经解决了这个问题。我不明白VBA会自动转换为String,因此在DLL中,我不是处理BSTR,而是使用ASCII char *或LPSTRs。此外,由于excel中的错误,从单元格内调用函数不会进行此转换。


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.

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.