未处理的异常:System.AccessViolationException:尝试读取或写入 [英] Unhandled Exception: System.AccessViolationException: Attempted to read or write
本文介绍了未处理的异常:System.AccessViolationException:尝试读取或写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的C ++ DLL
Below is my c++ DLL
// DLL.cpp : Defines the exported functions for the DLL application.
#include "stdafx.h"
//#include <stdexcept>
#include<iostream>
using namespace std;
typedef void (*FunctionPtr)(int);
void (*FunctionPtr1)(int);
extern "C" __declspec(dllexport)void Caller();
extern "C" __declspec(dllexport)void RegisterFunction(FunctionPtr func_ptr);
extern void Caller()
{
int i = 10;
FunctionPtr1(i);
}
extern void RegisterFunction(FunctionPtr func_ptr1)
{
FunctionPtr1 = func_ptr1;
}
这DLL会refernce从C#和通函数名参数C#功能。这里
是我的C#代码
This DLL will get refernce to function name from c# and pass arguments to c# function.. here is my c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace test
{
class Program
{
[DllImport("C:/Users/10602857/Documents/Visual Studio 2010/Projects/DLL/Debug/DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void Caller();
[DllImport("C:/Users/10602857/Documents/Visual Studio 2010/Projects/DLL/Debug/DLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern fPointer RegisterFunction(fPointer aa);
static void Main(string[] args)
{
Console.WriteLine("DLL Linking");
fPointer abc = new fPointer(ping);
RegisterFunction(abc); //send address of function to DLL
Caller(); //call from DLL
}
public delegate void fPointer(int s); // point to every functions that it has void as return value and with no input parameter
public static void ping(int a)
{
Console.WriteLine("ping executed " + a);
}
public static void add1()
{
Console.WriteLine("add executed");
}
}
}
C#代码能够得到我在C ++ DLL paseed如下
c# code is able to get the value which i paseed in c++ dll as below
int i = 10;
FunctionPtr1(i);
m到处的sedired输出,但progrram得到了在最后坠毁与以下execption
M getting the sedired output but progrram got crashed at the end with following execption
Unhandled Exception: System.AccessViolationException: Attempted to read or write
protected memory. This is often an indication that other memory is corrupt.
at test.Program.Caller()
为什么我收到这个?
why i am getting this ??
推荐答案
所有我需要做的是..
刚刚宣布我的委托作为...
All i need to do is.. just declare my delegate as ...
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyDelegate();
这篇关于未处理的异常:System.AccessViolationException:尝试读取或写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文