gpt4 book ai didi

c# - C 中的 allocVector() 和 System.AccessViolationException : Attempted to read or write protected memory?

转载 作者:太空宇宙 更新时间:2023-11-04 03:38:01 25 4
gpt4 key购买 nike

我对 allocVector() 函数有疑问。我用 C 编写了一个可以在 R 中调用的代码 (DLL)。我想将该 DLL 的一个方法调用到我在 C# 中的应用程序中。 DLL 代码工作正常,但是当编译器到达下一行 ROut = allocVector(INTSXP, 2*3)它给出以下异常:未处理的异常:System.AccessViolationException:试图读取或写入 protected 内存。代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <R.h>
#include <Rinternals.h>
#include <Rmath.h>
#include <R_ext/Applic.h>
#include <R_ext/Lapack.h>
#include <Rdefines.h>
#ifdef __cplusplus
extern "C" {
#endif
void castType(int *result)
{
SEXP ROut;
ROut = allocVector(INTSXP, 2*3)
ROut = PROTECT(ROut);
int *clustOut = INTEGER(ROut);
result= clustOut ;
}
#ifdef __cplusplus
}
#endif

最佳答案

快速阅读,我认为您使用值 6 作为指针的值。那里还有其他问题。

退而求其次,我为您的 C#/C 互操作提出了一些建议:

  • 如果您在这个 API 中没有很多自己的现有 C 代码,我建议您将它移植到 C# 并使用 R.NET(NuGet packagesource code)
  • 如果您确实有大量的 C/C++ 代码,或者绝对需要 C 层,您可以看看这个 sample code .在回答之前,我把它放在一起测试了几件事,所以我不妨提交源代码。

为了其他读者,从问题中的功能阐述它的症结是:

C API:

void c_api_call(int * result)
{
SEXP p = some_R_calculations();
int* int_ptr = INTEGER_POINTER(p);
int n = length(p);
for (int i = 0; i < n; i++)
result[i] = int_ptr[i];
// We are done with p; irrespective of where some_R_calculations got it,
// we can notify the R GC that this function releases it.
R_ReleaseObject(p);
}

C# 互操作包装器:

public class CppInterop : DynamicInterop.UnmanagedDll // http://www.nuget.org/packages/DynamicInterop/
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _c_api_call([In, Out] [MarshalAs(UnmanagedType.LPArray)] int[] values);

public int[] CreateArray()
{
// These two following references could be cached for efficiency later on.
var getLength = this.GetFunction<_c_api_call_getlength>("c_api_call_getlength");
var getValues = this.GetFunction<_c_api_call>("c_api_call");

// As far as I know it is preferable, if not needed, to handle arrays in two steps:
// we need to know the expected length to allocate in C# buffer memory.
int expectedLength = getLength();
int[] result = new int[expectedLength];
getValues(result);
return result;
}

关于c# - C 中的 allocVector() 和 System.AccessViolationException : Attempted to read or write protected memory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com