从 Intptr 到 Double[] 执行 marshal.copy 时出现访问冲突错误
Access Violation Error while doing marshal.copy from Intptr to Double[]
这不是实际代码。但我想在我的实际代码中做类似的事情。即将从 C# 获取双指针,并将 vaules 填充到 cpp 代码中,并将 marshal.copy 从 IntPtr 到 double [] 到 C# 代码中。这就是我尝试过的。但它会导致访问冲突。
C++代码:
__declspec(dllexport) void FillDoubleValues(IN UInt64 _NumSamplesToCapture, OUT double* pSamples)
{
for (int i = 0; i < _NumSamplesToCapture; i++)
{
pSamples[i] = (double)rand() / RAND_MAX;
}
}
C#:
[DllImport("LibOperation.dll", CallingConvention = CallingConvention.Cdecl)]
static public extern voi FillDoubleValues( [IN] UInt64 _NumSamplesToCapture, out IntPtr pSamples);
void main(){
UInt64 NumSamplesToCapture = 5000;
Intptr Sample;
FillDoubleValues(NumSamplesToCapture, out Sample);
double[] ys1 = new double[NumSamplesToCapture];
Marshal.Copy(Samples, ys1, 0, ys1.Length);
// ys1 wil be used to plot values
}
Marshal.Copy 给出错误 "System.AccessViolationException: 'Attempted to read or write protected memory. This is often indication that other memory is corrupt."
我在这里犯的任何错误。
提前致谢。
只需使用常规数组编组,无需自己编组
[DllImport("LibOperation.dll", CallingConvention = CallingConvention.Cdecl)]
static public extern void FillDoubleValues(UInt64 _NumSamplesToCapture, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] double[] pSamples);
void main()
{
UInt64 NumSamplesToCapture = 5000;
double[] ys1 = new double[NumSamplesToCapture];
FillDoubleValues(NumSamplesToCapture, ys1);
}
这不是实际代码。但我想在我的实际代码中做类似的事情。即将从 C# 获取双指针,并将 vaules 填充到 cpp 代码中,并将 marshal.copy 从 IntPtr 到 double [] 到 C# 代码中。这就是我尝试过的。但它会导致访问冲突。
C++代码:
__declspec(dllexport) void FillDoubleValues(IN UInt64 _NumSamplesToCapture, OUT double* pSamples)
{
for (int i = 0; i < _NumSamplesToCapture; i++)
{
pSamples[i] = (double)rand() / RAND_MAX;
}
}
C#:
[DllImport("LibOperation.dll", CallingConvention = CallingConvention.Cdecl)]
static public extern voi FillDoubleValues( [IN] UInt64 _NumSamplesToCapture, out IntPtr pSamples);
void main(){
UInt64 NumSamplesToCapture = 5000;
Intptr Sample;
FillDoubleValues(NumSamplesToCapture, out Sample);
double[] ys1 = new double[NumSamplesToCapture];
Marshal.Copy(Samples, ys1, 0, ys1.Length);
// ys1 wil be used to plot values
}
Marshal.Copy 给出错误 "System.AccessViolationException: 'Attempted to read or write protected memory. This is often indication that other memory is corrupt."
我在这里犯的任何错误。
提前致谢。
只需使用常规数组编组,无需自己编组
[DllImport("LibOperation.dll", CallingConvention = CallingConvention.Cdecl)]
static public extern void FillDoubleValues(UInt64 _NumSamplesToCapture, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] double[] pSamples);
void main()
{
UInt64 NumSamplesToCapture = 5000;
double[] ys1 = new double[NumSamplesToCapture];
FillDoubleValues(NumSamplesToCapture, ys1);
}