excel - 尝试在 Delphi 中构建 Excel RTD 服务器
问题描述
我正在尝试在 Delphi 中为 Excel 构建 RTD 服务器,但我无法让这部分代码工作:
function TRtdServer.RefreshData(var TopicCount: Integer): PSafeArray;
//Called when Excel is requesting a refresh on topics. RefreshData will be called
//after an UpdateNotify has been issued by the server. This event should:
//- supply a value for TopicCount (number of topics to update)
//- The data returned to Excel is an Object containing a two-dimensional array.
// The first dimension represents the list of topic IDs.
// The second dimension represents the values associated with the topic IDs.
var
Data : OleVariant;
begin
//Create an array to return the topics and their values
//note:The Bounds parameter must contain an even number of values, where each pair of values specifies the upper and lower bounds of one dimension of the array.
Data:=VarArrayCreate([0, 1, 0, 0], VT_VARIANT);
Data[0,0]:=MyTopicId;
Data[1,0]:=GetTime();
if Main.Form1.CheckBoxExtraInfo.Checked then Main.Form1.ListBoxInfo.Items.Add('Excel called RefreshData. Returning TopicId: '+IntToStr(Data[0,0])+' and Value: '+Data[1,0]);
TopicCount:=1;
// RefreshTimer.Enabled:=true;
//Result:=PSafeArray(VarArrayAsPSafeArray(Data));
Result:=PSafeArray(TVarData(Data).VArray);
end;
我不确定这部分:
Result:=PSafeArray(TVarData(Data).VArray);
但它可以是代码的任何部分。Excel 只是在包含 rtd() 函数调用的单元格中不显示任何结果。我确实设法在 Excel 第一次调用我的“ConnectData”函数时将结果输入单元格,该函数简单地返回一个字符串而不是 PSafeArray(尽管对该函数的第一次调用未能产生结果(N/A)。只有在 RTD() 调用中更改主题后,它会显示结果(仅一次))
我将代码基于来自https://blog.learningtree.com/excel-creating-rtd-server-c/的 C# 示例
谁能指出我正确的方向?
解决方案
OleVariant
拥有它持有的数据,并在其超出范围时释放该数据。PSafeArray
因此,您正在返回一个指向 Excel的无效指针。您需要:
在返回之前释放数组指针的所有权:
function TRtdServer.RefreshData(var TopicCount: Integer): PSafeArray; var Data : OleVariant; begin ... Result := PSafeArray(TVarData(Data).VArray); TVarData(Data).VArray = nil; // <-- add this end;
用于
SafeArrayCopy()
制作数组的副本,然后返回副本:uses ..., ActiveX; function TRtdServer.RefreshData(var TopicCount: Integer): PSafeArray; var Data : OleVariant; begin ... OleCheck( SafeArrayCopy( PSafeArray(TVarData(Data).VArray), Result ) ); end;
推荐阅读
- flutter - Firebase 通知不会发出声音或振动颤动
- pandas - pandas.series 和折线图相关问题
- postgresql - 从 React->ExpressJS->Postgres 修补 Postgres JSONB 列的最佳方法是什么?
- java - Java jar“manifest.mf(没有这样的文件或目录)”MacOS
- c++ - 数组无法在函数内正确播放 - 冒泡排序
- svn - 在没有多次提交目录属性的情况下忽略 svn repo 工作副本中某些文件的修改
- ios - 如何在 SwiftUI 中将 textField 键盘的“返回”按钮更改为蓝色的“完成”按钮?
- python-3.x - Python 3 - 在位置 p 的两个矩阵中对 2 个布尔值应用 AND 运算
- powershell - 如何使批处理文件在 vscode 终端中运行
- mongodb - 聚合MongoDB 3.4