系统.从c#调用到不安全的c++时的AccessViolationException
System.AccessViolationException when calling from C# to unsafe C++
我正在编写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。这意味着我试图访问受保护的内存…
//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/调用或本机函数foo
签名的问题。除了c++数组语法和RandomFunction
的作用之外,一切都很好。我刚刚用我自己的小演示进行了测试:
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编译所有内容。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- ostream过载时的缓冲区冲洗
- 具有未知值时的时间复杂性
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 当比特(而不是字节)的顺序至关重要时的持久性
- 旋转模型矩阵时的形状失真
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 打印第二列时的2d字符矢量打印空间
- 读取文件时运行时的未知行为
- posix_spawn():使用posix_scawn()时的错误处理问题
- 查找最近配对时的OpenMP竞赛条件
- 如何修复valgrind启动时的致命错误(与libc6-dbg和libc6-dbg:i386连接)
- 在 c++ 中在开关情况下使用和不使用"break"时的不同输出
- 求和 int 乘以双倍时的欠/过近似
- 打包可变参数模板具有零元素时的递归
- 在Qt5中使用QTextSteam时的"使用已删除功能"
- 内存错误低于在C++年实现埃拉托色尼筛分时的预期
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何将GTest与CMake一起使用?遵循谷歌指南时的链接问题