VBA / Excel和C ++ DLL,用绳子具体问题(VBA/Excel, and C++ DL

2019-09-28 18:26发布

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.

Answer 1:

GSerg已经解决了这个问题。 我不理解如通过字符串时,这样的DLL,我没有处理BSTRs但与ASCII字符*或LPSTRs是VBA自动转换。 此外,由于在Excel中的错误,从内细胞不会做这种转换调用函数。



文章来源: VBA/Excel, and C++ DLL, specifically problems with strings