如何在 C++ 中创建和初始化双精度 SAFEARRAY 以传递给 C# [英] How to create and initialize SAFEARRAY of doubles in C++ to pass to C#
问题描述
我的 C# 方法需要从 C++ 调用
My C# method needs to be invoked from C++
最初我的 C# 方法采用 double[] 类型的参数,但是当从 C++ 调用时,它变成了 SAFEARRAY
Originally my C# method takes a parameter of type double[], but when calling from C++ it becomes a SAFEARRAY
在 C++ 中,我需要从双精度数组中获取数据,并填充 SAFEARRAY.我还没有找到任何示例代码来执行此操作.
In C++ I need to take data from an array of doubles, and populate a SAFEARRAY. I have not found any sample code to do this.
感谢任何帮助
推荐答案
以下是在 C++ 中创建安全数组的代码.
Following is the code to create a safearray in C++.
#include<oaidl.h>
void CreateSafeArray(SAFEARRAY** saData)
{
double data[10]; // some sample data to write into the created safearray
SAFEARRAYBOUND Bound;
Bound.lLbound = 0;
Bound.cElements = 10;
*saData = SafeArrayCreate(VT_R8, 1, &Bound);
double HUGEP *pdFreq;
HRESULT hr = SafeArrayAccessData(*saData, (void HUGEP* FAR*)&pdFreq);
if (SUCCEEDED(hr))
{
// copy sample values from data[] to this safearray
for (DWORD i = 0; i < 10; i++)
{
*pdFreq++ = data[i];
}
SafeArrayUnaccessData(*saData);
}
}
完成后释放指针,如以下代码-
Free the pointer when you are finished like the following code-
SAFEARRAY* saData;
CreateSafeArray(&saData); // Create the safe array
// use the safearray
...
...
// Call the SafeArrayDestroy to destroy the safearray
SafeArrayDestroy(saData);
saData = NULL; // set the pointer to NULL
如果您将 ATL 用于 C++,那么最好使用在atlsafe.h"中声明的 CComSafeArray.这是 SAFEARRAY 的包装器.链接文本
If you use ATL for C++, then better use CComSafeArray declared in "atlsafe.h". This is wrapper for SAFEARRAY. link text
这篇关于如何在 C++ 中创建和初始化双精度 SAFEARRAY 以传递给 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!