从C++(非托管代码)检索数组到 C 尖锐形式(托管)

Retrieving array from C++(Unmanaged code) to C Sharp form(Managed)

本文关键字:托管 数组 C++ 非托管代码 检索      更新时间:2023-10-16

我在C++中有以下实现(创建了相同的DLL(

double *getData()
{
double *eyeTrackData = new double[10];
const unique_ptr<Fove::IFVRHeadset> headset{ Fove::GetFVRHeadset() };
CheckError(headset->Initialise(Fove::EFVR_ClientCapabilities::Gaze), 
"Initialise");
Fove::SFVR_GazeVector leftGaze, rightGaze;
const Fove::EFVR_ErrorCode error = headset->GetGazeVectors(&leftGaze, 
&rightGaze);

// Check for error
switch (error)
{
case Fove::EFVR_ErrorCode::None:
eyeTrackData[0] = (double)leftGaze.vector.x;
eyeTrackData[1] = (double)leftGaze.vector.y;
eyeTrackData[2] = (double)rightGaze.vector.x;
eyeTrackData[3] = (double)rightGaze.vector.y;
break;

default:
// Less common errors are simply logged with their numeric value
cerr << "Error #" << EnumToUnderlyingValue(error) << endl;
break;
}
return eyeTrackData;
}

我已经包括

extern "C"
{
__declspec(dllexport) double *getData();
}

在头文件中。

我尝试在 C 尖锐中接收这个。

[DllImport("C:\Users\BME 320 - Section 1\Documents\Visual Studio 2015\Projects\EyeTrackDll\x64\Debug\EyeTrackDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr eyeData();

但是我不知道如何接收按钮单击事件中的数组。

我感谢这方面的任何帮助。

按照@DavidHeffernan提示,我将尝试为您提供一个如何实现目标的示例。请将 C# 部分作为伪代码,因为我不是该语言的专家。

我会像前面所说的那样使用结构体,只是为了让事情更清楚,我认为提供一些类型保护是一种很好的做法,如果不知道确切有多少双精度值,可以向结构添加"size"属性。在您的情况下,一如既往地是 4,不需要。

C++库中的功能:

void getData(double* eyeTrackData)
{
const unique_ptr<Fove::IFVRHeadset> headset{ Fove::GetFVRHeadset() };
CheckError(headset->Initialise(Fove::EFVR_ClientCapabilities::Gaze), "Initialise");
Fove::SFVR_GazeVector leftGaze, rightGaze;
const Fove::EFVR_ErrorCode error = headset->GetGazeVectors(&leftGaze, &rightGaze);

// Check for error
switch (error)
{
case Fove::EFVR_ErrorCode::None:
eyeTrackData[0] = (double)leftGaze.vector.x;
eyeTrackData[1] = (double)leftGaze.vector.y;
eyeTrackData[2] = (double)rightGaze.vector.x;
eyeTrackData[3] = (double)rightGaze.vector.y;
break;
default:
// Less common errors are simply logged with their numeric value
cerr << "Error #" << EnumToUnderlyingValue(error) << endl;
break;
}
}

C# 端:

[DllImport("C:\Users\BME 320 - Section 1\Documents\Visual Studio 2015\Projects\EyeTrackDll\x64\Debug\EyeTrackDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void eyeData(IntPtr); 
private void button1_Click(object sender, EventArgs e) 
{ 
try 
{ 
IntPtr ipr = Marshal.AllocHGlobal(4); // Memory blob to pass to the DLL
eyeData(ipr);
double[] eyeTrackData = new double[4]; // Your C# data
Marshal.Copy(ipr, eyeTrackData, 0, 4); // Convert?
}
finally 
{ 
Marshal.FreeHGlobal(ipr); 
}
} 

再次,对不起我的"糟糕的 C#"xD。希望这有帮助。