c# - 从 C# 调用不安全的 C++ 时出现 System.AccessViolationException

标签 c# c++ c arrays struct

我正在编写导入 C++ 函数的 C# 代码,与此类似:

//C++ code
extern "C" _declspec(dllexport) int foo(double *var1, double *var2){
    double dubs[10];
    RandomFunction(dubs);
    *var1 = dubs[5];
    *var2 = dubs[7];
    return 0;
}

为了将此函数导入 C#,我尝试了 2 种方法,但都导致了 System.AccessViolationException。这意味着我正在尝试访问 protected 内存...

//C# import code
//method 1
[DllImport(example.dll,CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern int foo(ref double var1, ref double var2);
//method 2
[DllImport(example.dll,CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern int foo(double *var1, double *var2);

//C# calling code
//method 1
public unsafe int call_foo(){
    ....Stuff
    double var1 = 0;
    double var2 = 0;
    foo(ref var1, ref var2);
    ....More Stuff
}
//method 2
public unsafe int call_foo(){
    ....Stuff
    double var1 = 0;
    double var2 = 0;
    double *v1 = &var1;
    double *v2 = &var2;
    foo(v1, v2);
    ....More Stuff
}

到目前为止,我一直认为这是我的 C# 代码的问题,但 C++ 代码对数组的使用会导致问题吗?我在这里错过了一些非常明显的东西吗?

最佳答案

这不是您的 C# p/调用或 native 函数 foo 的签名的问题。除了您的 C++ 数组语法和 RandomFunction 的确切功能之外,一切正常。我刚刚用我自己的小演示进行了测试:

C++:

void RandomFunction( double dubs[] );

extern "C" __declspec(dllexport) int foo ( double* var1, double* var2 ) 
{
    double dubs[10];

    RandomFunction( dubs );

    *var1 = dubs[5];
    *var2 = dubs[7];

    return 0;
}

void RandomFunction( double dubs[] ) {
    for ( int i = 0; i < 10; i++ ) {
        dubs[i] = i;
    }
}

C#:

[DllImport( "Native.dll", CallingConvention = CallingConvention.Cdecl )]
private static extern int foo( ref double var1, ref double var2 );

public static void Main( string[] args )
{
    FooTest();
}

private static void FooTest()
{
    double var1 = 0;
    double var2 = 0;

    foo( ref var1, ref var2 );

    Console.Out.WriteLine( "Var1: {0:0.0}; Var2: {1:0.0}", var1, var2 );
    // Prints "Var1: 5.0; Var2: 7.0"
}

我和你的只有一点点不同:

  • 我的 C++ 数组是使用标准语法 double dubs [10] 声明的。
  • 我的编译器要求 __declspec 语法中有两个下划线
  • 我在 Windows 7 SP 1 上使用 64 位 Visual Studio 2012 编译所有内容。

关于c# - 从 C# 调用不安全的 C++ 时出现 System.AccessViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616419/

相关文章:

c# - 在多线程程序中使用 EF 的好建议?

c# - 如何使用 LINQ 和 EF Core 在树状层次结构中找到第一个父级

c++ - 如何过滤掉 std::variant vector 中某些数据类型的元素?

c++ - 在 C++11 中实现线程安全方法的正确方法

c++ - 如何创建和使用类型为 "customClass"的列表

c - 通过 Malloc 增加分配给结构的内存大小

c# - TFS Fakes 构建单元测试失败

c# - GetLastWriteTime 返回 12/31/1600 7 :00:00 PM

c - 如何确保信号处理程序完成,然后才继续程序?

c - 链表 - C