c - 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?
解决方案
参考我的一个旧项目,我做了以下事情(翻译了一下你的项目)。
在 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 部分,您现在返回一个字符串,但似乎您想返回原始字节。您只需放入 即可做到这一点TempChar
,Response[i]
而无需使用sprintf
. 仅将Response
其视为字节缓冲区,而不是 VBA 字符串类型。
推荐阅读
- javascript - 有没有办法将堆积条形图与 Apexcharts(或类似)一起使用并分离数据?
- python - 使用 Python Speech Client 从 Google Speech 向文本 API 请求“获取操作”
- reactjs - 你应该如何*确切*使用useContext?
- javascript - 将 script.js 链接到 html
- java - 捕获异常后我可以继续事务操作吗?
- java - 如何在 java/android 中将 JPG 图像转换为字符串
- android - 如何阻止 RecyclerView 中的视图在获得焦点时更新其值?
- mysql - .Net Core 3 Mysql Pomelo DateTime 不兼容
- java - 为什么在编写 UnitTest 时得到空响应
- c# - 以表格形式显示今天的日期(asp.net core)