首页 > 解决方案 > How to call a C DLL from a VBA application and return an array?

问题描述

I'm developing a a VBA application which writes and reads a serial port through a C DLL. In the code below I have managed to return a value into the VBA code in the form of a string.

What I want to do is call the function in the DLL and have the returned value inserted into an array. I also don't want to use the split function to parse the string into and array after I get it back as my implementation of VBA does not have access to that function.

C DLL Function

void FAR PASCAL RxReadResponse(char* Response)
{
    char TempChar; //Temporary character used for reading
    char SerialBuffer[100];//Buffer for storing Rxed Data
    DWORD NoBytesRead;
    int i = 0;
    char buf [20];
    char bufFull [256];
    long num;
    long streamLenght;
    do
     {
          ReadFile( hComm,           //Handle of the Serial port
                    &TempChar,       //Temporary character
                    sizeof(TempChar),//Size of TempChar
                    &NoBytesRead,    //Number of bytes read
                    NULL);


          SerialBuffer[i] = TempChar;// Store Tempchar into buffer
          sprintf(buf,"%x",TempChar& 0xFF);
          strcat(bufFull, buf);

          if(i==0)
           {
              num = (int)TempChar;
              streamLenght = num + 4;
           }

          i++;
     }
    while (i < streamLenght);

    lstrcpy (Response, bufFull);
}

VBA Declaration

Declare Function RxReadResponse Lib "CDLL" (ByRef rxRead As String) As String

VBA Button Click

Sub Button2_EventClick()
Dim This As Object : Set This = Button2

    Dim s

    s = RxReadResponse

    EditBox6.Text = s


End Sub 

The Returned String

0FB34CB45AB24BB45A4CB45AB24BB45A

Desired Outcome in VBA

s(0) = OF
s(1) = B3
s(2) = 4C
     .
     .
     .
s(16) = 5A

What do I need to do differently?

标签: carraysvba

解决方案


参考我的一个旧项目,我做了以下事情(翻译了一下你的项目)。

在 C 中:

char * __stdcall RxReadResponse(char* Response)
{
    //....
    return Response;
}

在 VBA 中:

Declare Function RxReadResponse Lib "CDLL" ( _
        ByVal Response As String _
) As String

Sub Button2_EventClick()
    Dim s As String
    s = String(256, vbNullChar) 'string (storage) of 256 null chars

    s = RxReadResponse (s)
    '....
End Sub 

我希望这可以帮助你在 VBA 部分。

至于 C 部分,您现在返回一个字符串,但似乎您想返回原始字节。您只需放入 即可做到这一点TempCharResponse[i]而无需使用sprintf. 仅将Response其视为字节缓冲区,而不是 VBA 字符串类型。


推荐阅读