c#调用c++的dll出现尝试读取或写入受保护的内存问题

使用c#调用c++的一个dll。c++的接口函数为:

extern "C" __declspec(dllexport)bool __stdcall CreateDetmObject(IDetManager **ppDetManager);

参数IDetManager为一个结构体:

   struct IDetManager
  {
    virtual void __stdcall SetListener(HWND hWnd) = 0;
    virtual bool __stdcall OpenDetector(const char *strIniFile) = 0;
    virtual bool __stdcall CloseDetector() = 0;
    }

在c#端对接口函数和结构体重新定义如下:

        [DllImport(DllName)]
        public extern static bool CreateDetmObject(ref IDetManager ppDetManager);

                [StructLayout(LayoutKind.Sequential)] 
        public class IDetManager
        {
            public IntPtr SetListener;
            public IntPtr OpenDetector;
            public IntPtr CloseDetector;
                }

c#调用代码如下:

            Tzb.CInterface.IDetManager iDetManager = new Tzb.CInterface.IDetManager();
            CInterface.CreateDetmObject(ref iDetManager);

            Func<bool> closeDetector = (Func<bool>)Marshal.GetDelegateForFunctionPointer(iDetManager.CloseDetector, typeof(Func<bool>)); 
            closeDetector();

但每次运行到CInterface.CreateDetmObject(ref iDetManager);时,程序崩溃,提示错误:
“System.AccessViolationException”类型的未经处理的异常出现在 Tzb.exe 中。
其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

不知是我的c#代码哪里出了错误,希望大家可以多多帮助。

3个回答

指针有越界等,先看是DLL中指针问题还是你的C#调用的问题

public class IDetManager
->
public struct IDetManager

alexsun6
alexsun6 好像是可以啊,Func<bool> closeDetector = (Func<bool>)Marshal.GetDelegateForFunctionPointer(iDetManager.CloseDetector, typeof(Func<bool>)); 执行时报错:其他信息: 指定的类型不得是泛型类型定义。是什么原因?
接近 4 年之前 回复

把c++代码加到c#工程中调试。如果不是调用方式出现问题,那就是c++代码在频繁操作一个不存在或错误指针。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c#调用c++的dll出现尝试读取或写入受保护的内存问题
使用c#调用c++的一个dll。c++的接口函数为:rn[code=c]extern "C" __declspec(dllexport)bool __stdcall CreateDetmObject(IDetManager **ppDetManager);[/code]rn参数IDetManager为一个结构体:rn[code=c] rnstruct IDetManagerrn rn virtual void __stdcall SetListener(HWND hWnd) = 0;rn virtual bool __stdcall OpenDetector(const char *strIniFile) = 0;rn virtual bool __stdcall CloseDetector() = 0;rn rn[/code]rn在c#端对接口函数和结构体重新定义如下:rn[code=csharp] rn [DllImport(DllName)]rn public extern static bool CreateDetmObject(ref IDetManager ppDetManager);rnrn [StructLayout(LayoutKind.Sequential)] rn public class IDetManagerrn rn public IntPtr SetListener;rn public IntPtr OpenDetector;rn public IntPtr CloseDetector;rn rn[/code]rnc#调用代码如下:rn[code=csharp] rnTzb.CInterface.IDetManager iDetManager = new Tzb.CInterface.IDetManager();rnCInterface.CreateDetmObject(ref iDetManager);rnrnFunc closeDetector = (Func)Marshal.GetDelegateForFunctionPointer(iDetManager.CloseDetector, typeof(Func)); rncloseDetector();rn[/code] rn但每次运行到CInterface.CreateDetmObject(ref iDetManager);时,程序崩溃,提示错误:rn“System.AccessViolationException”类型的未经处理的异常出现在 Tzb.exe 中。rn其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn不知是我的c#代码哪里出了错误,希望大家可以多多帮助。
c#调用c++ 尝试读取或写入受保护的内存
c#调用c++ 尝试读取或写入受保护的内存,怎么解决rnrnc++ API:rn[code=csharp]rnvoid MD_InitMessageInfo(rn MD_MessageInfo* MessageInfo // pointer to MD_MessageInfo structrn)rnrnThe MD_InitMessageInfo structure initializes an MD_MessageInfo structure inrnpreparation for sending an email message using MD_SpoolMessage.rnrnParametersrnrn MessageInfo - pointer to an MD_MessageInfo structure. This members of thisrn structure are cleared and the priority member is set torn MD_PRECEDENCE_NORMAL.rnrnRemarksrnrn You should call this function immediately after declaring an MD_MessageInforn structure.rnrnExamplernrn MD_MessageInfo MessageInfo;rn MD_InitMessageInfo(&MessageInfo);[/code]rnrnrnc# APIrnrn[code=csharp]MDUser.InitMessageInfo MessageInfornrnThis method initializes the MessageInfo object in preparation for sending an email message rnusing MDUser.SpoolMessage.rnrnParametersrnrn MessageInfo - MDMessageInfo ojbect. The priority attribute is set torn MD_PRECEDENCE_NORMAL.rnrnRemarksrnrn You should call this method immediately after creating an instance of the MDMessageInfo object.rn[/code]rnrnrn[code=csharp] MDUser mdu = new MDUser();rn MDMessageInfo MessageInfo = new MDMessageInfo();rnrn MessageInfo.To = "test1@ceshi.com";rn MessageInfo.From = "test2@ceshi.com";rn MessageInfo.Subject = "邮件主题";rn MessageInfo.MessageBody = "邮件正文内容";rnrn mdu.InitMessageInfo(MessageInfo);[/code]rnrnrn程序运行到 InitMessageInfo 异常:尝试读取或写入受保护的内存rnrn
尝试读取或写入受保护的内存
前提是:其他的应用程序内存地址(0x012E6F54),如何读取它和改变它rn unsafern rn uint* ptr = (uint*)0x012E6F54;rn MessageBox.Show((*ptr).ToString()); rn //这里出现错误:尝试读取或写入受保护的内存rn rnrn
DeviceIoControl 出现"尝试读取或写入受保护的内存"
调试程序的时候 If DeviceIoControl(Device, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, dwBytesReceived, 0) = 0 Then 这句话被绿出来了,然后提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”rnrnrn以下是源码:rn Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integerrn Private Declare Function DeviceIoControl Lib "kernel32" Alias "DeviceIoControl" (ByVal hDevice As Integer, ByVal dwIoControlCode As Integer, ByVal lpInBuffer As Integer, ByVal nInBufferSize As Integer, ByVal lpOutBuffer As Integer, ByVal nOutBufferSize As Integer, ByVal lpBytesReturned As Integer, ByVal lpOverlapped As Integer) As Integerrn Private Declare Function DefineDosDevice Lib "kernel32" Alias "DefineDosDeviceA" (ByVal dwFlags As Integer, ByVal lpDeviceName As String, ByVal lpTargetPath As String) As Integerrn Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (ByVal hObject As Integer) As Integerrn Private Const GENERIC_READ = &H80000000rn Private Const GENERIC_WRITE = &H40000000rn Private Const FILE_SHARE_READ = &H1rn Private Const FILE_SHARE_WRITE = &H2rn Private Const OPEN_EXISTING = 3rn Private Const FILE_FLAG_NO_BUFFERING = &H20000000rn Private Const INVALID_HANDLE_VALUE = -1rn Private Const IOCTL_FILE_DISK_CLOSE_FILE = &H8000E004rn Private Const FSCTL_DISMOUNT_VOLUME = &H90020rn Private Const FSCTL_LOCK_VOLUME = &H90018rn Private Const FSCTL_UNLOCK_VOLUME = &H9001Crn Private Const DDD_REMOVE_DEFINITION = &H2rnrn Private Sub UninstUSB(ByRef nDrive As String)rn Dim Device As Integerrn nDrive = "\\.\" & nDrive & ":"rn Device = CreateFile(nDrive, GENERIC_READ Or GENERIC_WRITE, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0&, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, 0)rn If Device = INVALID_HANDLE_VALUE Thenrn Console.WriteLine("Cannot open drive")rn Console.WriteLine("Operate failed")rn Exit Subrn Elsern Console.WriteLine("Open drive succeed")rn End Ifrn Dim dwBytesReceived As Integerrn If DeviceIoControl(Device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, dwBytesReceived, 0) = 0 Then Console.WriteLine("Cannot lock drive")rn If DeviceIoControl(Device, IOCTL_FILE_DISK_CLOSE_FILE, 0, 0, 0, 0, dwBytesReceived, 0) = 0 Then Console.WriteLine("Cannot close file of drive")rn [color=#008000]If DeviceIoControl(Device, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, dwBytesReceived, 0) = 0 Then[/color]rn Console.WriteLine("Cannot unmount drive")rn Console.WriteLine("Operate failed")rn Exit Subrn End Ifrn If DeviceIoControl(Device, FSCTL_UNLOCK_VOLUME, 0, 0, 0, 0, dwBytesReceived, 0) = 0 Then Console.WriteLine("Cannot unlock drive")rn If CloseHandle(Device) = 0 Then Console.WriteLine("Cannot close device handle")rn If DefineDosDevice(DDD_REMOVE_DEFINITION, nDrive, vbNullString) = 0 Thenrn Console.WriteLine("Cannnot delete drive letter")rn Console.WriteLine("Operate failed")rn Exit Subrn End Ifrn Console.WriteLine("Operate SUCCESS")rn Console.WriteLine()rn End Sub
c#调用c++ dll出现“尝试读取或写入受保护的内存”
C++ 原型方法 [img=https://img-bbs.csdn.net/upload/201812/07/1544155020_697311.png][/img],[img=https://img-bbs.csdn.net/upload/201812/07/1544155031_442585.png][/img],rn我在C# 里面使用的时候[img=https://img-bbs.csdn.net/upload/201812/07/1544155177_210828.png][/img],求解决方案!
C#调用C++的DLL出现 尝试读取或写入受保护的内存 求救
C++函数rn__stdcall FUNCTIONA(CString ab,byte *ad);rnrnc#rnint32 FUNCTIONA(String ab,ref Byte[] ad);rnrn[size=13px][color=#FF0000]调用的时候出现“尝试读取或写入受保护的内存”rn请问该如何解决[/color][/size]
C#调用C++的DLL 出现:“尝试读取或写入受保护的内存”
最近做的项目,外壳是用C#写的,核心代码使用C++写的。在C#调用C++的DLL的过程中发现了以下的错误:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn 以下是C++的函数实现:rn#pragma comment(linker, "/SECTION:MYSEC,RWS") rnrn#pragma data_seg("MYSEC") rnrnchar ResultBuffer[10000]; //ResultBuffer 是共享数据段中的一个char型数组,用来实现跨进程通信的rnrn#pragma data_seg() rnextern "C" __declspec(dllexport) char* GetRecordInfo()rnrn OutputDebugStringA(ResultBuffer);rn return ResultBuffer; rnrnrnC#下函数声明如下:rn [DllImport("HooksLib.dll")]rn public static extern StringBuilder GetRecordInfo();rnrn调用时,可以在DbgView中看到 ResultBuffer的值是正确的,但是在C#的代码中发生了尝试读取或写入受保护的内存。这通常指示其他内存已损坏的错误。rn原来猜想是C#和C++中Char长度不一样,C#占两个字节,C++一个字节的问题,但是把Char转成了wchar_t也还是错。rn花了两天时间,没能解决问题。希望有哪位高手,指导下。rn
C# 调用dll函数,出现尝试读取或写入受保护的内存
C# 调用dll函数rn 出现:尝试读取或写入受保护的内存。这通常指示其他内存已损坏.这是什么意思?急急!
c# 编写ActiveX调用c++编写的dll 出现"尝试读取或写入受保护的内存"
我用c#编写了一个ActiveX控件,其中调用过了c++编写的dll,在程序运行的时候出现了“尝试读取或写入受保护的内存”的错误信息。但这个c++的dll在C#编写的WinForm下是运行正常的。下面是ActiveX的源代码rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Drawing;rnusing System.Data;rnusing System.Text;rnusing System.Runtime.InteropServices;rnusing System.Windows.Forms;rnrnnamespace ReaderCTRrnrn [ComImport, GuidAttribute("8173BE03-E29B-49CB-A4B4-52778F6E37E5")]rn [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]rn public interface IObjectSafetyrn rn [PreserveSig]rn int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions);rnrn [PreserveSig()]rn int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions);rn rnrn [GuidAttribute("8173BE03-E29B-49CB-A4B4-52778F6E37E5"), ProgId("ReaderCTR.MyAxControlTest"), ComVisible(true)]rnrn public partial class MyAxControlTest : UserControl, IObjectSafetyrn rnrn [DllImport("M1Reader.dll", EntryPoint = "ResetReader", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]rn static extern byte ResetReader();rn rn public MyAxControlTest()rn rn InitializeComponent();rn rnrn #region IObjectSafety Membersrnrn public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)rn rn pdwSupportedOptions = 1;rn pdwEnabledOptions = 2;rn return 0;rn rnrn public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)rn rn return 0;rn rnrn #endregionrnrn private void button1_Click(object sender, EventArgs e)rn rn byte a = ResetReader(); //***出错的就是这一句。rn rnrn rn
c#调用c++ dll出现“尝试读取或写入受保护的内存”提示
用c++写的一个调用pcl功能的dll,在c++控制台下工作正常,写成dll提供c#调用时,却出现“尝试读取或写入受保护的内存”的提示。分别调整了CallingConvention的参数,结果如下:rn CallingConvention.Winapi:尝试读取或写入受保护的内存。rn CallingConvention.ThisCall:Debug Assertion Failed!提示窗口。rn CallingConvention.StdCall:尝试读取或写入受保护的内存。rn CallingConvention.StdCall:无效的非托管调用约定: 必须是 stdcall、cdecl 或 thiscall 之一。rn CallingConvention.Cdecl:尝试读取或写入受保护的内存。rnrn代码如下:rn[code=csharp]rn[System.Runtime.InteropServices.DllImport(@"D:\新整理\开发\MSC++\PCLLibs\PCLTest\Debug\PCLTest.dll", EntryPoint = "PLYConvert", CallingConvention = CallingConvention.Cdecl)]rn public extern static int PLYConvert(string pcdPath, string savePath, float searchRadius, float mu, int nearestNeighbors);rnrn private void Form1_Load(object sender, EventArgs e)rn rn PLYConvert(@"D:\新整理\安装与资源\点云数据集\PCDdata\bunny.pcd", @"d:\bunny.ply", 15.0f, 5.0f, 100);rn MessageBox.Show("ok");rn rn[/code]rn代码是调用PCLTest.dll中的PLYConvert方法,将pcd转为ply。dll的dumpbin查询结果如下:rn[code=text]rnDump of file pcltest.dllrnrnFile Type: DLLrnrn Section contains the following exports for PCLTest.dllrnrn 00000000 characteristicsrn 5B3603A8 time date stamp Fri Jun 29 18:02:16 2018rn 0.00 versionrn 1 ordinal basern 1 number of functionsrn 1 number of namesrnrn ordinal hint RVA namernrn 1 0 000444C5 PLYConvert = @ILT+17600(_PLYConvert)rnrn Summaryrnrn 3000 .datarn 5000 .idatarn 18000 .rdatarn 5000 .relocrn 1000 .rsrcrn 8B000 .textrn 3F000 .textbssrn 1000 .tlsrn[/code]rnrn请教如何解决该问题?
C# 尝试读取或写入受保护的内存
[code=C#]FileStream fs = new FileStream(pdfpath,FileMode.Open,FileAccess.Read);rn byte[] fileCount = new byte[fs.Length];rn fs.Read(fileCount, 0, fileCount.Length);rn fs.Close();rn Decrypt(ref fileCount);rn axFoxitPDFSDK1.OpenBuffer(fileCount, fileCount.Length, "");[/code]rnaxFoxitPDFSDK1是一个第三方组件,用阅读PDF文件的.这样,虽然能阅读,但总是报错,[color=#FF0000]尝试读取或写入受保护的内存,这通常指示其他内存已损坏.[/color],无论我怎样去释放fs使用的资源,都没用,怎么回事?
急!!C# 调用c的DLL时提示“尝试读取或写入受保护内存...”
下面是c++DLL中的声明:rnint __stdcall sp_pp_card_get_track(char *trk2, char *trk3, char *pan)rnint __stdcall sp_pp_des_pin(char *pan, unsigned char *des_pin)rn我在c#中调用该DLL时该怎么样声明呢?大家帮帮忙啊,我试了好多种数据类型,要么程序直接关掉,要么提示尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
c#尝试读取或写入受保护的内存
private static object BytesToStuct(byte[] bytes, Type type)rn rn // int size = Marshal.SizeOf(type);rn int size = bytes.Length;rn if (size > bytes.Length)rn rn return null;rn rn IntPtr structPtr = Marshal.AllocHGlobal(size);rn Marshal.Copy(bytes, 0, structPtr, size);rn object obj = Marshal.PtrToStructure(structPtr, type);rn Marshal.FreeHGlobal(structPtr);rn rn return obj;rn rnrn怎么会有下面的错误的呢,大侠们快来帮忙啊rnrnrn有关调用实时(JIT)调试而不是此对话框的详细信息,rn请参见此消息的结尾。rnrn************** 异常文本 **************rnSystem.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn 在 System.Runtime.InteropServices.Marshal.PtrToStructureHelper(IntPtr ptr, Object structure, Boolean allowValueClasses)rn 在 System.Runtime.InteropServices.Marshal.PtrToStructure(IntPtr ptr, Type structureType)rn 在 GM_TOOL.ClientOnlineManger.BytesToStuct(Byte[] bytes, Type type)rn 在 GM_TOOL.ClientOnlineManger.online_usersearch_btn_Click(Object sender, EventArgs e)rn 在 System.Windows.Forms.Control.OnClick(EventArgs e)rn 在 System.Windows.Forms.Button.OnClick(EventArgs e)rn 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)rn 在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)rn 在 System.Windows.Forms.Control.WndProc(Message& m)rn 在 System.Windows.Forms.ButtonBase.WndProc(Message& m)rn 在 System.Windows.Forms.Button.WndProc(Message& m)rn 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)rn 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)rn 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)rnrnrn************** 已加载的程序集 **************rnmscorlibrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3615 (GDR.050727-3600)rn 基本代码: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dllrn----------------------------------------rnmscorlib.resourcesrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3615 (GDR.050727-3600)rn 基本代码: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dllrn----------------------------------------rnGM_TOOLrn 程序集版本: 1.0.0.0rn Win32 版本: 1.0.0.0rn 基本代码: file:///C:/Documents%20and%20Settings/Administrator/桌面/Debug/GM_TOOL.exern----------------------------------------rnSystem.Windows.Formsrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3053 (netfxsp.050727-3000)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dllrn----------------------------------------rnSystemrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3614 (GDR.050727-3600)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dllrn----------------------------------------rnSystem.Drawingrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3053 (netfxsp.050727-3000)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dllrn----------------------------------------rnSystem.Configurationrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3053 (netfxsp.050727-3000)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dllrn----------------------------------------rnSystem.Xmlrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3082 (QFE.050727-3000)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dllrn----------------------------------------rnzlib.netrn 程序集版本: 1.0.3.0rn Win32 版本: 1.0.3.0rn 基本代码: file:///C:/Documents%20and%20Settings/Administrator/桌面/Debug/zlib.net.DLLrn----------------------------------------rnSystem.Windows.Forms.resourcesrn 程序集版本: 2.0.0.0rn Win32 版本: 2.0.50727.3053 (netfxsp.050727-3000)rn 基本代码: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms.resources/2.0.0.0_zh-CHS_b77a5c561934e089/System.Windows.Forms.resources.dllrn----------------------------------------rnrn************** JIT 调试 **************rn要启用实时(JIT)调试,rn该应用程序或计算机的 .config 文件(machine.config)的 system.windows.forms 节中必须设置rnjitDebugging 值。rn编译应用程序时还必须启用rn调试。rnrn例如: rnrnrn rnrnrn启用 JIT 调试后,任何无法处理的异常rn都将被发送到在此计算机上注册的 JIT 调试器,rn而不是由此对话框处理。
C# 调用C写的dll ,传递结构一直报 尝试读取或写入受保护的内存
C# 调用C写的dll ,传递结构一直报 尝试读取或写入受保护的内存,rn知道是结构对应的问题,可是这个对应好难搞啊, 没学过C。rn有没有什么调试的方法,或者变通的方法?rn看到说可以把结构转成byte[] 来传递, 大神告诉我是什么机制, 要怎么搞~~~rn求帮助
C#调用C dll 报错:尝试读取或写入受保护的内存
C#调用C写的dll,参数中有一个int型的指针,一运行就报如题的错误,大家帮忙看下问题。其它的参数就忽略不写了哈。rnC代码:rnextern "C" __declspec(dllexport) int c_func(..., int* outdatalen)rnrn .......rn *outdatalen = 4; // 假如要返回给C#的值rn ........rnrnrnC#代码rn[DllImport("xxx.dll")]rnpublic static extern unsafe int c_func(..., int* outdatalen);rnrnpublic unsafe int sql_func(...,ref int outdatalen) //其它参数省略rnrn int ret = 0;rn rn int len = outdatalen;rn ret = c_func(..., &len); // 调用C dll函数rn outdatalen = len;rn return ret;rnrnrn代码已经简化,只列出问题部分,望参与讨论或给出解答。先行谢过。
C# 尝试读取或写入受保护的文件
C# 一个类A里面写了一个线程,线程里面是调用另外一个应用程序(此应用程序里面的窗体上放了一个C++写的控件)上放的控件里面的一些方法。线程里面调用完之后我都用窗体dispose()的.rn 一个类B频繁调用A里面的那个线程,但是时不时会报那个错误,rn我感觉这个问题是因为我之前的窗体没释放掉,然后下一次又在用,但是不太确定。。。。 很急的问题,求解啊。。rnrn稍后贴代码块。。。rnrn
升级框架到net4.0后,调用DLL 出现 尝试读取或写入受保护的内存错误
错误提示:尝试读取或写入受保护的内存,这通常指示其它内存已损坏rnrnrn1.原项目由VS2008编写而成,后换成Vs2015。未更改目标框架,运行程序一切正常rnrn2. 通过右键项目 > 应用程序框架, 将主程序及出问题的DLL由原来的3.5改成4.0rn运行主程序并打开任意一个网页时,在页面加载完成的瞬间,出现如下图的错误,错误出现在名为extendedWebbroswer 的DLL里(这个DLL是webbrowser扩展组件,实现点击链接时新页面时在原窗口上打开,不跳出新窗口)。rnrn[img=https://img-bbs.csdn.net/upload/201610/09/1475999143_339094.png][/img]rnrn[color=#808080]上图的错误提示里的msoffice.dll 应为 extendedWebbroswer.dll[/color] rnrn由于不太看得懂DLL里的内容,原提供者也找不着了,在此请教,感谢!rnrnrn
VB.net调用C++的dll出现 尝试读取或写入受保护的内存
下面是dll的说明rnint createMessage(char * authMessage,rnint* authMessageLength,rn char * sn,rn int * snLen)rn构建认证消息包. 自动判断用户是否已登录,根据临时信息构建相应的消息包。rn注:authMessage、authMessageLength、sn、snLen四个参数为出口参数,但需调用程序初始化相应大小的内存块。一般建议authMessage内存块长度为2500个字节以上,sn内存块长度为100个字节以上,以保证API数据有足够的内存进行存放。authMessageLength和sn分别为两个内存块的长度值。rn参数说明:rnIN:无rnOUT:rnauthMessage: API构建的认证消息包,为Base64编码rnauthMessageLength: 认证消息长度rnsn:用户证书序列号rnsnLen:用户序列号的长度rn返回值:rn0: 构建正确rn<0: 构建错误rnrnrn上面是C++组建的说明rn下面是我用调用的过程rn< _rn Public Function CreateMessage(ByVal Authmessage As String, ByVal Authmessagelen As Integer, ByVal ByValSn As String, ByVal Snlen As Integer) As Integerrn End Functionrnrn程序中这样调用,但是报错“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”rn Dim X As Integerrn Dim a As String = ""rn Dim b As String = ""rn Dim c As Integer = 0rn Dim d As Integer = 0rn X = CreateMessage(a, c, b, d)rnrn
c#调用C++ DLL 尝试读取或写入受保护的内存
[code=C#] [ StructLayoutAttribute( LayoutKind.Sequential)]rn public struct tagNkMAIDEnumrn /// ULONG->unsigned intrn public uint ulType;rn /// ULONG->unsigned intrn public uint ulElements;rn /// ULONG->unsigned intrn public uint ulValue;rn /// ULONG->unsigned intrn public uint ulDefault;rn /// SWORD->shortrn public short wPhysicalBytes;rn /// LPVOID->void*rn public IntPtr pData;rn rn [ StructLayoutAttribute( LayoutKind.Sequential)]rn public struct tagNkMAIDObjectrn /// ULONG->unsigned intrn public uint ulType;rn /// ULONG->unsigned intrn public uint ulID;rn /// NKREF->LPVOID->void*rn public IntPtr refClient;rn /// NKREF->LPVOID->void*rn public IntPtr refModule;rn rnrn rn [DllImportAttribute("Type0003.md3", EntryPoint = "MAIDEntryPoint")]rn public static extern ForControl.eNkMAIDResult MAIDEntryPoint(ref ForControl.tagNkMAIDObject pObject,rn ForControl.eNkMAIDCommand ulCommand,rn uint ulParam,rn uint ulDataType,rn ref ForControl.tagNkMAIDEnum data,rn IntPtr pfnComplete,rn IntPtr refComplete);rn rn ForControl.tagNkMAIDObject Mod = new ForControl.tagNkMAIDObject();rn ForControl.tagNkMAIDEnum ModEnum;rnresult = MAIDEntryPoint(ref Mod, ForControl.eNkMAIDCommand.kNkMAIDCommand_CapGet, (uint)ForControl.eNkMAIDCapability.kNkMAIDCapability_Children, (uint)ForControl.eNkMAIDDataType.kNkMAIDDataType_EnumPtr, ref ModEnum, IntPtr.Zero, IntPtr.Zero);rn if (result != ForControl.eNkMAIDResult.kNkMAIDResult_NoError)rn return; rnrn if (ModEnum.wPhysicalBytes != 4)rn return; rn if (ModEnum.ulElements == 0)rn return; rn ModEnum.pData = Marshal.AllocHGlobal((int)(ModEnum.wPhysicalBytes * ModEnum.ulElements));rn //通过调用DLL函数将数据写入stEnum.pData 出错 显示尝试读取或写入受保护的内存。这通常指示其他内存已损坏。 rn [color=#FF0000]result = MAIDEntryPoint(ref Mod,rn ForControl.eNkMAIDCommand.kNkMAIDCommand_CapGetArray,rn (uint)ForControl.eNkMAIDCapability.kNkMAIDCapability_Children,rn (uint)ForControl.eNkMAIDDataType.kNkMAIDDataType_EnumPtr,rn PmodEnum, rn IntPtr.Zero,rn IntPtr.Zero);[/color]rn rn if (result != ForControl.eNkMAIDResult.kNkMAIDResult_NoError)rn return; [/code]rnrn[code=C/C++] rntypedef struct tagNkMAIDObjectrn rn ULONG ulType; // One of eNkMAIDObjectTypern ULONG ulID;rn NKREF refClient;rn NKREF refModule;rn NkMAIDObject, FAR* LPNkMAIDObject;rnrntypedef struct tagRefObjrn rn LPNkMAIDObject pObject;rn SLONG lMyID;rn LPVOID pRefParent;rn ULONG ulChildCount;rn LPVOID pRefChildArray;rn ULONG ulCapCount;rn LPNkMAIDCapInfo pCapArray;rn RefObj, *LPRefObj;rn typedef struct tagNkMAIDEnumrn rn ULONG ulType; // one of eNkMAIDArrayTypern ULONG ulElements; // total number of elementsrn ULONG ulValue; // current indexrn ULONG ulDefault; // default indexrn SWORD wPhysicalBytes; // bytes per elementrn LPVOID pData; // allocated by the clientrn NkMAIDEnum, FAR* LPNkMAIDEnum;rnBOOL SelectSource( LPRefObj pRefObj, ULONG *pulSrcID )rnrn BOOL bRet;rn NkMAIDEnum stEnum;rn char buf[256];rn UWORD wSel;rn ULONG i;rn LPNkMAIDCapInfo pCapInfo = GetCapInfo( pRefObj, kNkMAIDCapability_Children );rn if ( pCapInfo == NULL ) return false;rnrn // check data type of the capabilityrn if ( pCapInfo->ulType != kNkMAIDCapType_Enum ) return false;rn // check if this capability suports CapGet operation.rn if ( !CheckCapabilityOperation( pRefObj, kNkMAIDCapability_Children, kNkMAIDCapOperation_Get ) ) return false;rnrn bRet = Command_CapGet( pRefObj->pObject, kNkMAIDCapability_Children, kNkMAIDDataType_EnumPtr, (NKPARAM)&stEnum, NULL, NULL );rn if( bRet == false ) return false;rnrn // check the data of the capability.rn if ( stEnum.wPhysicalBytes != 4 ) return false;rnrn if ( stEnum.ulElements == 0 ) rn printf( "There is no Source object.\n0. Exit\n>" );rn scanf( "%s", buf );rn return true;rn rnrn // allocate memory for array datarn stEnum.pData = malloc( stEnum.ulElements * stEnum.wPhysicalBytes );rn if ( stEnum.pData == NULL ) return false;rn // get array data 通过调用DLL函数将数据写入stEnum.pData rn [color=#FF0000]bRet = Command_CapGetArray( pRefObj->pObject, kNkMAIDCapability_Children, kNkMAIDDataType_EnumPtr, (NKPARAM)&stEnum, NULL, NULL );[/color]rnrn if( bRet == false ) rn free( stEnum.pData );rn return false;rn rnrn // show the list of selectable Sourcesrn for ( i = 0; i < stEnum.ulElements; i++ )rn printf( "%d. ID = %d\n", i + 1, ((ULONG*)stEnum.pData)[i] );rnrn if ( stEnum.ulElements == 1 )rn printf( "0. Exit\nSelect (1, 0)\n>" );rn elsern printf( "0. Exit\nSelect (1-%d, 0)\n>", stEnum.ulElements );rnrn scanf( "%s", buf );rn wSel = atoi( buf );rnrn if ( wSel > 0 && wSel <= stEnum.ulElements ) rn *pulSrcID = ((ULONG*)stEnum.pData)[wSel - 1];rn free( stEnum.pData );rn else rn free( stEnum.pData );rn if ( wSel != 0 ) return false;rn rn return true;rn[/code]
C#调用dll “尝试读取或写入受保护的内存。这通常指示其他内存已损坏"
该DLL是将DICOM图片格式传到PIVIEW中。该程序在VC里已经实现,现要在C#里实现。dll里方法接口为BOOL __stdcall dicom_storescu_execute(LPCSTR servername, int serverport,rnLPCSTR servertitle, LPCSTR clienttitle, rnLPCSTR filelist, STORESCUCALLBACK callback);rn其中STORESCUCALLBACK 是一个函数指针typedef void (__stdcall * STORESCUCALLBACK)(T_StoreProgress* progress);。rn调用为:rn isSuccessed = dicom_storescu_execute(TheadIPadress,rn TheadServerPort ,rn TheadServerTitle,rn TheadClientTitle, rn TheadImageFile ,rn MyStoreScuCallback);rnMyStoreScuCallback为一函数名rn在C#中rnpublic delegate void STORESCUCALLBACK(T_StoreProgress progress);rn[DllImport("dcmtrans.dll", EntryPoint = "dicom_storescu_execute")]rn public static extern bool dicom_storescu_execute(string servername,rn int serverport, string servertitle, string clienttitle,rn string filelist, STORESCUCALLBACK callback);rn调用为rnrn internal unsafe void startSCU(Object lpParam)rn rn StoreSCUThead scu_CS = (StoreSCUThead)lpParam;rn string TheadIPadress = scu_CS.strIPadress;rn int TheadServerPort = scu_CS.strServerPort;rn string TheadServerTitle = scu_CS.strServerTitle;rn string TheadClientTitle = scu_CS.strClientTitle;rn string TheadImageFile = scu_CS.strImageFile;rn int mxh = scu_CS.Theadxh;rn bool isSuccessed = false;rn STORESCUCALLBACK callback = new STORESCUCALLBACK(MyStoreScuCallback);rn isSuccessed = dicom_storescu_execute(TheadIPadress,rn TheadServerPort,rn TheadServerTitle,rn TheadClientTitle,rn TheadImageFile,rn callback);rnrn if (!isSuccessed)rn falseNum++;rn rnrnMyStoreScuCallback为函数名rn public void MyStoreScuCallback(T_StoreProgress progress)rn rn switch (progress.state)rn rn case T_StoreProgressState.StoreBegin:rn break;rn case T_StoreProgressState.StoreProgressing:rn break;rn case T_StoreProgressState.StoreEnd:rn break;rn default:rn break;rn rn rn其中startSCU是开辟一个线程调用的rn internal unsafe void OnSend(string path)rn rn string m_aetitle="";rn string m_ip = "";rn int m_port = 0;rn string m_Filename = "";rn string m_path = "";rn StringBuilder m_tmp = new StringBuilder(255);rn m_Filename = path + "test.dcm";rn m_path = path + "user_setting.ini";rn GetPrivateProfileString("SetupDCM", "aetitle", null, m_tmp, 15, m_path);rn m_aetitle = m_tmp.ToString();rn GetPrivateProfileString("SetupDCM" , "ip" , null , m_tmp , 15 , m_path);rn m_ip = m_tmp.ToString();rn GetPrivateProfileString("SetupDCM", "port", null, m_tmp, 15, m_path);rn m_port = Int32.Parse(m_tmp.ToString());rn StoreSCUThead uStoreSCUThead = new StoreSCUThead();rn uStoreSCUThead.strIPadress = m_ip;rn uStoreSCUThead.strServerPort = m_port;rn uStoreSCUThead.strServerTitle = "OPACS";rn uStoreSCUThead.strClientTitle = m_aetitle;rn uStoreSCUThead.strImageFile = m_Filename;rn uStoreSCUThead.Theadxh = 1;rn //Thread fThread = new Thread(new ThreadStart(startSCU));rn Thread fThread = new Thread(startSCU);rn fThread.Start(uStoreSCUThead);rn fThread.Join(1000);rn rn一编译就出错在调用函数dicom_storescu_execute“这报尝试读取或写入受保护的内存”的错。请问各位大哥,我是不是函数指针转化的类型出错啦?而且我把MyStoreScuCallback里参数换为不是指针类型的了。这些有影响吗?rnrnrn
C# 调用c++ dll 尝试读取或写入受保护的内存 错误
typedef enum _KEY_STATUSrn KEY_OFFLINE = 0,rn KEY_ONLINE = 1,rn KEY_LOGIN = 2rn KEY_STATUS;rn USBKey_GetDevState(IN KEYHANDLE hKey, OUT KEY_STATUS *pKeyStatus);//c++ dll导出文件类型rnrnrnrn我的调用rn[DllImport("USBKey.dll", EntryPoint = "USBKey_GetDevState")]rn public static extern UInt32 USBKey_GetDevState(IntPtr hkey,ref UInt32 status);rn或者rn[DllImport("USBKey.dll", EntryPoint = "USBKey_GetDevState")]rn public static extern UInt32 USBKey_GetDevState(IntPtr hkey,out UInt32 status);rn都是出现上述错误 望高手指教啊!rn
C#调用dll “尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
编译OK,调试时候显示的错误rn尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rnrn************** 异常文本 **************rnSystem.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn 在 HZbox.HZjudge.DoRecognize(Byte[] byteSerializedCh, Int32 iByteNum, Int16 chDestCh, Int16& chWrittenCh, Double[] pEvalout, Int32 iENum, Int32[] state, Byte[] ch)rn 在 HZbox.HZjudge.Judge() 位置 I:\GoogleCode\hzapp\HZcomponent.HZbox\HZjudge.cs:行号 114rnrnrndll是C++的,是写.def的方式导出的方法rn原来的声明是这样的rn[code=C/C++]rnBOOL DoRecognize(rn const unsigned char* pWriteData, rn const int iDataLen, rn const unsigned short iDestWChar,rn unsigned short* iWrittenChar, rn double* pEvalOut, rn const int iENumber,rn int *state,rn char *cs);rn[/code]rn用在C#里我写成了rn[code=C#]rn[DllImport(@"C:\Windows\System32\RIT.dll", EntryPoint="DoRecognize")]rnstatic extern int DoRecognize(rn byte[] byteSerializedCh,rn int iByteNum,rn short chDestCh,rn ref short chWrittenCh,rn double[] pEvalout,rn int iENum,rn int[] state,rn byte[] ch);rn[/code]rn总觉得是不是类型错了。rnrn另外还有一点不知道值不值得一说,rn这个dll回读取txt文件的,一开始调用是文件读不到,所以我把dll读取的文件路径都改成了绝对路径,放在system32下。rn然后就变成了这样的错误,请高手指教~
高手请进 c# 调用c++ dll 提示尝试读取或写入受保护的内存
[DllImport("HDWheelDllTwo.dll", EntryPoint = "?SetWorkStatus@CHDlib@@QAEXHHNH@Z", CharSet = CharSet.Auto,CallingConvention=CallingConvention.Cdecl)]rn//public static extern void SetWorkStatus(Int32 nDiameter, Int32 nWorkStatus, double dPSI, Int32 nLModel);也是一样的rnpublic static extern void SetWorkStatus(int nDiameter,int nWorkStatus, double dPSI,int nLModel);rn在这样调用的时候 SetWorkStatus(1200, 1, 100,1);报“尝试读取或写入受保护的内存,这通常指其他内存已损坏”错误,c++函数原型为:rnvoid SetWorkStatus(int nDiameter,int nWorkStatus,double dPSI,int nLModel);rn烦请给位大神给点儿思路,给点儿想法,急需甘露啊!!!!rn
C# 调用C++ DLL提示“尝试读取或写入受保护的内存。”
我要用C#调用C++的DLL(里面是关于DES加密的算法),但是调用是有时会报错提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”rnC#调用的代码:rn [DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]rn public static extern string desEncrypt2(string keyText, string plainText);rnrnC++代码:rnchar *desEncrypt2(char *encryptedText, const char *plainText)rn rn unsigned char buf[9];rn char hex[17];rnrn unsigned char longbuf[512+1];rn char longhex[512*2+1];rnrn memset(buf, 0, sizeof(buf));rn memset(hex, 0, sizeof(hex));rn memset(longbuf, 0, sizeof(longbuf));rn memset(longhex, 0, sizeof(longhex));rnrn strncpy((char *)longbuf, plainText, sizeof(longbuf)-1); //平台移植到2008的需要,strncpy->strncpy_srn int index;rn for (index = 0; longbuf[index]; index += 8)rn rn memcpy(buf, longbuf+index, 8);rn DesEncrypt(key, buf);rn for (int i=0; i < 8; i++)rn sprintf(hex+2*i, "%02x", buf[i]);rn memcpy(longhex+2*index, hex, 16);rn rnrn [color=#FF0000]strcpy(encryptedText, longhex);rn[/color]rn return encryptedText;rn rn很可能是strcpy(encryptedText, longhex);这句导致的,但是去掉直接返回longhex又是乱码。rn我在网上找了很久,有说分配的内存空间没有释放,请问“unsigned char longbuf[512+1];char longhex[512*2+1];”,这两个要释放的吗?不是动态分配啊,我不大懂C++麻烦各位帮忙了。rn另外,我用的是VS2010的平台
c#调用delphi编写的DLL文件报错,尝试读取或写入受保护的内存.
这个问题比较诡异,我在网上搜了很久都没找到答案,rnC#调用DELPHI写的DLL,调用其中一个方法:rn[code=C#]rnrn public static string 显示柜台返回信息()rn rnrn StringBuilder pDataBack = new StringBuilder();rn pDataBack.Capacity = 300000;rn readAnswer(ThreadNo, UniNumber, dwCommObj, ref pDataBack);rn string temp = pDataBack.ToString();rnrn return temp;rn rn rn[/code]rn其中 readAnswer(ThreadNo, UniNumber, dwCommObj, ref pDataBack);rn是调用delphi编写的DLL文件里的接口,其中 pDataBack 是在调用之后回写的参数,也就是说在DLL里会对该参数重新赋值,现在问题是,如果赋值的字符比较小,则正常通过,如果赋值的内容过多,则会报错,如下:rn[code=VB]rnrn未处理的异常: System.AccessViolationException: 尝试读取或写入受保护的内存。这通rn常指示其他内存已损坏。rn 在 SingleFunctionBetter.ReadAnswer.Invoke(Int32 ThreadNo, Int32 UniNumber, Inrnt32 dwCommObj, StringBuilder& pDataBack)rn 在 SingleFunctionBetter.Fixture.显示柜台返回信息() 位置 C:\guangda\test\Fixturnre.cs:行号 111rn 在 SingleFunctionBetter.Fixture.Main(String[] args) 位置 C:\guangda\test\Fixtrnure.cs:行号 249rn请按任意键继续. . .rnrn[/code]rnrn我把 ref 改成 out也不行,我给pDataBack设置容量 pDataBack.Capacity = 300000;也不行,返回字符肯定小于3万rn实在没招了~,在此发帖给大家,希望帮我解决一下,感激不尽~!
c#调用c++ dll提示 尝试读取或写入受保护的内存
查了n遍百度,都找不解决不了,只有上来求大牛帮帮忙了。。。。rnrn直接上代码:rnrnc++ dll代码rnrn文件: HookApi.hrnrn#include rn#ifndef _HOOKAPI_Hrn#define _HOOKAPI_Hrnrnclass HookApi rnpublic:rn LPVOID pOldFunEntry, pNewFunEntry ; // 初始函数地址、HOOK后的函数地址rn BYTE bOldByte[5], bNewByte[5] ; // 原始字节、目标字节rnrnpublic:rn HookApi () rn ~HookApi() rn // 实现HOOK APIrn void Hook (PSTR szModuleName,PSTR szFunName,FARPROC pFun)rn rn HMODULE hMod = ::GetModuleHandleA ( szModuleName ) ;rn if (hMod != NULL)rn rn pNewFunEntry = (LPVOID)pFun ;rn pOldFunEntry = (LPVOID)GetProcAddress ( hMod, szFunName ) ;rn bNewByte[0] = 0xE9 ;rn *((PDWORD)(&(bNewByte[1]))) = (DWORD)pNewFunEntry -(DWORD)pOldFunEntry - 5 ; rnrn DWORD dwProtect, dwWriteByte, dwReadByte ; rn VirtualProtect ( (LPVOID)pOldFunEntry, 5, PAGE_READWRITE, &dwProtect );rn ReadProcessMemory ( GetCurrentProcess(), (LPVOID)pOldFunEntry, bOldByte, 5, &dwReadByte ) ; rn WriteProcessMemory ( GetCurrentProcess(), (LPVOID)pOldFunEntry, bNewByte, 5, &dwWriteByte ) ;rn VirtualProtect ( (LPVOID)pOldFunEntry, 5, dwProtect, NULL ) ;rn rn rn // 重新HOOKrn void ReHook ()rn rn DWORD dwProtect, dwWriteByte ;rn VirtualProtect ( pOldFunEntry, 5, PAGE_READWRITE, &dwProtect );rn WriteProcessMemory ( GetCurrentProcess(), pOldFunEntry, bNewByte, 5, &dwWriteByte ) ;rn VirtualProtect ( pOldFunEntry, 5, dwProtect, NULL ) ;rn rn // 撤消HOOKrn void UnHook ()rn rn DWORD dwProtect, dwWriteByte ;rn VirtualProtect ( pOldFunEntry, 5, PAGE_READWRITE, &dwProtect );rn WriteProcessMemory ( GetCurrentProcess(), pOldFunEntry, bOldByte, 5, &dwWriteByte ) ;rn VirtualProtect ( pOldFunEntry, 5, dwProtect, NULL ) ;rn rn ;rnrn#endifrnrn文件 dllmain.cpprnrn// dllmain.cpp : 定义 DLL 应用程序的入口点。rn#include "stdafx.h"rnrn#include "HookApi.h";rnHookApi HookItem;rnrn// 定义MessageBoxA函数原型rntypedef int (WINAPI* PFNMessageBoxA)( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType ) ;rnrn// 自定义的MessageBoxA函数rn// 实现对原始MessageBoxA的输入、输出参数的监控,甚至是取消调用rnint WINAPI New_MessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType )rnrn // 撤消HOOKrn HookItem.UnHook () ;rn rn PFNMessageBoxA pfnMessageBoxA = (PFNMessageBoxA)HookItem.pOldFunEntry ;rn rn // 调用原函数,修改输入参数rn int ret = pfnMessageBoxA ( hWnd, "这是HOOK函数过程的消息框", "[测试]", uType ) ;rn rn HookItem.ReHook () ;rn rn return ret ;rnrnrn extern "C" __declspec(dllexport) void abc() rn rn // HOOK APIrn MessageBoxA ( 0, "正常消息框", "测试", 0 ) ;rn HookItem.Hook("USER32.dll","MessageBoxA",(FARPROC)New_MessageBoxA) ;rn rnrnBOOL APIENTRY DllMain( HMODULE hModule,rn DWORD ul_reason_for_call,rn LPVOID lpReservedrn )rnrnrn switch (ul_reason_for_call)rn rn case DLL_PROCESS_ATTACH:rn case DLL_THREAD_ATTACH:rn case DLL_THREAD_DETACH:rn case DLL_PROCESS_DETACH:rn break;rn rn return TRUE;rnrn上面代码编译成:CHook.dllrnrnc#代码很简单rnrn public partial class Form1 : Formrn rn [DllImport("CHook.dll")]rn public static extern void abc();rn public Form1()rn rn InitializeComponent();rn rnrn private void button1_Click(object sender, EventArgs e)rn rn abc();//点这里开始调用c++ hook ,没报错,证明已经运行了rn rnrn private void button2_Click(object sender, EventArgs e)rn rn MessageBox.Show("aaa");//这里报错,尝试读取或写入受保护的内存rn rn rnrnrn请问,那里错了,c++水平不怎么样,很郁闷。。。。rnrn大牛们救救小弟。。。。。
C# 调用DLL一个方法提示尝试读取或写入受保护的内存
这个方法在头文件中是这样声明的rnrn[code=C/C++]rnCP5200API int CALLING_CONV CP5200_MakeCreateFileData(HOBJECT hObj, BYTE *pBuffer, int nBufSize, const char* pFilename, long lFilesize, const BYTE* pTimeBuffer);rn[/code]rnrn而我在C#是这样声明的rnrn[code=C#]rn[DllImport( m_strPath, CharSet = CharSet.Auto )]rn public static extern int CP5200_MakeCreateFileData( IntPtr hObj, byte[] pBuffer, int nBufSize, byte[] pFilename, long lFilesize, byte[] pTimeBuffer );rn[/code]rnrn调用代码部分代码如下:rn[code=C#]rnIntPtr hobj = CPower.CP5200.CP5200_CommData_Create( 0, 1, 0 );rn byte[] buffer = new byte[512];rn string filename = "test.txt";rn CPower.CP5200.CP5200_MakeCreateFileData( hobj, buffer, 512, System.Text.Encoding.Default.GetBytes( filename ), 32, new byte[6] 11, 2, 3, 4, 5, 6 );rn[/code]rnrn我很菜,所以望各位大虾们能说详细一点,我已经在这里郁闷很久了,谢谢rn
c#调用DLL尝试读取或写入受保护的内存。这通常指示其他内存已损坏
DELPHI里dll的源码rnrnrnfunction Init(const CDT:integer):integer;stdcall;rn //释放对象 =0成功;=1失败rn function UnInit:integer;stdcall;rn //主机初始化com口函数 =0成功;=1失败rn function InitCom(const comid:string):integer;stdcall;rn //设置读写器状态 =0成功;=1失败rn function SetState(const state:integer):integer;stdcall;rn //读取卡号 =1失败rn function ReadCard(buffer: PChar; bufferlen: integer):integer;stdcall;rn //写信息到卡片中 =0成功;=1失败 mark=0 默认密码FF FF FF FF FF FF =1 新密码 d2 bb c3 f9 cc ecrn function WriteInfo(const mark:integer;const id:integer; const d1:integer;const d2:integer;const d3:integer;const d4:integer;rn const d5:integer;const d6:integer;const d7:integer;const d8:integer;const d9:integer;rn const d10:integer;const d11:integer;const d12:integer;const d13:integer;const d14:integer;rn const d15:integer;const d16:integer):integer;stdcall;rn //读信息到卡片中 =0成功;=1失败 mark=0 默认密码FF FF FF FF FF FF =1 新密码 d2 bb c3 f9 cc ecrn function ReadInfo(const mark:integer;const id:integer;d1:PChar;d2:PChar;d3:PChar;d4:PChar;d5:PChar;d6:PChar;d7:PChar;rn d8:PChar;d9:PChar;d10:PChar;d11:PChar;d12:PChar;d13:PChar;d14:PChar;d15:PChar;d16:PChar):integer;stdcall;rn //*******************内部函数**************************rn //设置发送数据标识rn function SetMark(const handle:THandle;const mark:byte):integer;rn //发送数据函数 =0成功;=1失败 =3 mark位设置失败rn function SendData(const handle:THandle):integer;rn //接收数据函数 =0成功;=1失败 =11 接收失败 =12 接收头错误 =5 超时错误rn function InceptData(const handle:THandle):integer;rn //计算效验值 //mark=1 读,=0 写rn function ComputeEfficacy(mark:integer):integer;rn我调用C#调用rnrn [DllImport("Project2.dll")]rn private static extern int Init(int CDT);rn //释放对象 =0成功;=1失败rn [DllImport("Project2.dll")]rn private static extern int UnInit();rnrn //主机初始化com口函数 =0成功;=1失败rn [DllImport("Project2.dll")]rn private static extern int InitCom(string comid);rn //设置读写器状态 =0成功;=1失败rn [DllImport("Project2.dll")]rn private static extern int SetState(int state);rn //读取卡号 =1失败rn [DllImport("Project2.dll")]rn private static extern int ReadCard(ref string buffer, byte bufferlen);rn //写信息到卡片中 =0成功;=1失败 mark=0 默认密码FF FF FF FF FF FF =1 新密码 d2 bb c3 f9 cc ecrn [DllImport("Project2.dll")]rn private static extern int WriteInfo(int mark,int id,int d1, int d2, int d3,int d4,int d5,int d6,int d7, int d8,int d9,int d10,int d11,int d12,int d13,int d14,int d15,int d16);rnrn //读信息到卡片中 =0成功;=1失败 mark=0 默认密码FF FF FF FF FF FF =1 新密码 d2 bb c3 f9 cc ecrn [DllImport("Project2.dll")]rn private static extern int ReadInfo(int mark,int id,ref string d1,ref string d2,ref string d3,ref string d4,ref string d5,ref string d6,ref string d7,ref string d8,ref string d9,ref string d10,ref string d11,ref string d12,ref string d13,ref string d14,ref string d15,ref string d16);rn //*******************内部函数**************************rn //设置发送数据标识rn [DllImport("Project2.dll")]rn private static extern int SetMark(ref IntPtr handle, byte mark);rn //发送数据函数 =0成功;=1失败 =3 mark位设置失败rn [DllImport("Project2.dll")]rn private static extern int SendData(IntPtr handle);rn //接收数据函数 =0成功;=1失败 =11 接收失败 =12 接收头错误 =5 超时错误rn [DllImport("Project2.dll")]rn private static extern int InceptData( IntPtr handle);rn //计算效验值 //mark=1 读,=0 写rn [DllImport("Project2.dll")]rn private static extern int ComputeEfficacy(int mark);rn
C#调用C++编写的DLL出问题:尝试读取或写入受保护的内存
rnrn[img=https://img-bbs.csdn.net/upload/201504/07/1428382839_655005.png][/img]rnrn[code=java]rnnamespace WpfApplication2rnrn class MyClass1 : INotifyPropertyChanged rn rn public MyClass1()rn rn result="null";rn rn private string result;rn rn public string Resultrn rn get return result; rn set result = value;rn if (PropertyChanged != null)rn rn this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Result"));rn rn rn rn rn public event PropertyChangedEventHandler PropertyChanged;rn rn /// rn /// MainWindow.xaml 的交互逻辑rn /// rn public class transrn rn [DllImport("trans.dll")]rn public static extern int transmain(String exportpath, String importpath);rn rn public partial class Main : Windowrn rn rn MyClass1 myout=new MyClass1 (); rn private String exportpath; rn private String importpath; rn public Main()rn rn InitializeComponent();rn myout.Result = "there will show ,if transform is ok ";// Result 赋值应该放到Main的构造函数或者窗口的Loaded事件中赋值的。rn //把结果binding上去。。。请注意,XAML里的binding并不能访问C#里的变量,而C#里的变量却可以访问XAMLrn Binding bind1 = new Binding();rn bind1.Source = myout; rn bind1.Path = new PropertyPath("Result");rn this.MyLabel.SetBinding(Label.ContentProperty, bind1); rn rn rn rn public class transrn rn [DllImport("trans.dll")]rn public static extern int transmain(String exportpath, String importpath);rn rn private void Button_Click_2(object sender, RoutedEventArgs e)rn rn //int isornotsuccess = 1;rn int isornotsuccess = trans.transmain(exportpath, importpath);rn if(isornotsuccess==1)rn rn myout.Result = exportpath;rn Binding bind2 = new Binding(); rn bind2.Source = myout;rn bind2.Path = new PropertyPath("Result");rn this.MyLabel.SetBinding(Label.ContentProperty, bind2); //这里写成功后的反应rn rn rn rn private void textBox1_KeyDown_1(object sender, KeyEventArgs e)rn rn if (e.Key == Key.Enter) //key是一个类,这是一个类的判断rn rn exportpath=this.textBox1.Text;rn rn rn rn rn rn private void textBox2_KeyDown_1(object sender, KeyEventArgs e)rn rn if (e.Key == Key.Enter)rn rn importpath = this.textBox2.Text;rn rn rn rn rn rn rn rnrn rnrnrnrn[/code]rnrn------------------------------------------分割线------反汇编------------------------rn 101: //int isornotsuccess = 1;rn 102: int isornotsuccess = trans.transmain(exportpath, importpath);rn mov eax,dword ptr [ebp-3Ch] rn mov ecx,dword ptr [eax+000001D0h] rn mov eax,dword ptr [ebp-3Ch] rn mov edx,dword ptr [eax+000001D4h] rn call FFE8690C rn mov dword ptr [ebp-50h],eax rn mov eax,dword ptr [ebp-50h] rn mov dword ptr [ebp-44h],eax rn-----------------------------------------C++封装的外部接口------------------------------rnextern "C"_declspec(dllexport) int WINAPI transmain(char* exportpath ,char* importpath)rn----------------------------------------问题---------------------------------------------------rn我简单的陈述下。rn 首先数据类型, C++是char*所以C#是String,这没有问题。rn 其次exportpath这个参数,我确定有接收到。因为做过实验可以把exportpath的内容打出来。rnrn 中断发生在反汇编的第一行,实在不知为何请指教。 rnrn rnrnrn
C# 调用C开发的动态链接库DLL 报 尝试读取或写入受保护的内存。
[code=C#]rn//调用C的dll函数,函数前两个参数为入参,第三个为出参rn[DllImport("NhImp.dll", EntryPoint = "getMembers", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]rn public static extern int getMembers(ref string nd, ref string ylzh, StringBuilder members);rn[/code]rnrn[code=C#]rn//调用rnstring nd = "2012";rn string ylzh = "1412010103000029";rn StringBuilder YBOutBuf = new StringBuilder(10240);rn int retint = getNhMembers(ref nd, ref ylzh, YBOutBuf);rnrn[/code]rnrn一执行int retint = getNhMembers(ref nd, ref ylzh, YBOutBuf); 就报内存损坏错误,那位大侠指点下啊,谢谢!
C# 调用 C++的DLL 尝试读取或写入受保护的内存
C++ 原形rnDLL_EXPORT int WAPA_IPC_Dec(int index, unsigned char *instream, int istream_size, unsigned char *outstream); //解码,其中index为解码器的索引号,istream是编码数据,istream_size编码数据的大小,ostream为解码后的数据rnDLL_EXPORT int WAPA_IPC_SetDataCallBack(DataCallBack fData); //设置视频回调函数rntypedef BOOL (CALLBACK *DataCallBack)(int index, int type, BYTE* pData, int len, int param1, int param2);rnrnC#代码rn //解码,其中index为解码器的索引号,istream是编码数据,istream_size编码数据的大小,ostream为解码后的数据rn [DllImport("SDK.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]rn public static extern int WAPA_IPC_Dec(int index, [In, MarshalAs(UnmanagedType.LPStr)]StringBuilder instream, int istream_size, [Out, MarshalAs(UnmanagedType.LPStr)]StringBuilder outstream);rn //视频回调函数,index为摄像机索引,type为帧类型,pData为指向长度为len的帧数据的指针,bMove为TRUE表示这一帧的图像有移动,param1、param2为图像宽高rnrn [UnmanagedFunctionPointer(CallingConvention.Cdecl)]rn public delegate bool DataCallBack(int index, int type, [In, MarshalAs(UnmanagedType.LPStr)]StringBuilder pData, int len, int param1, int param2);rn 调用rnrn int i = DvrClinet.DvrInit(TVFORMAT.PAL);rn int m; StringBuilder _buildera;rn m = DvrClinet.DvrLogin("192.168.1.200", 0);rn int y = DvrClinet.DvrInitDec(1920, 1080, 264, 0);rn int n = DvrClinet.DvrGetCameraState(m);rn _buildera = new StringBuilder(1920 * 1080 * 2);rn DvrClinet.DvrSetDataCallBack(new DataCallBack(ShowDisplay));rn public bool ShowDisplay(int index, int type, [In, MarshalAs(UnmanagedType.LPStr)]StringBuilder pData, int len, int param1, int param2)rn rn byte[] ss = new byte[len];rn byte[] aa = new byte[len];rnrn IntPtr pImage = Marshal.AllocHGlobal(param1 * param2);rnrn // pData = new StringBuilder(len);rn DvrClinet.WAPA_IPC_Dec(m, pData, len, _buildera);//这里报错,尝试读取或写入受保护的内存rnrn //_buildera.Remove(0, _buildera.Length);rn //pData.Remove(0, _buildera.Length);rnrn MessageBox.Show(pData.Length.ToString()rn );rnrn return true;rn rnrn rnrn为什么 一调试就出现 尝试读取或写入受保护的内存的错误呢,请高手帮忙 要怎么改
C#调用DLL 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
// 参数: pstConvInfo 指向用来保存设备列表的缓存rn// iCount 为缓存中可保存多少个ST_CONVINFO结构。rn// iTimeOut 超时时间, 单位为毫秒rn// 返回: 搜索到的设备个数rnDLL_CONVERTER int CONV_FindConverter(ST_CONVINFO* pstConvInfo, int iCount, int iTimeOut);rn// 设备信息rn[code=c]typedef structrnrn char strMAC[20];rn char strIP[20];rnchar strUserName[64];rnchar strDeviceName[64];rnST_CONVINFO;[/code]rn以上是VC入口函数和结构体rnrn以下是C# 代码,请问大神们问题以下rnrn [code=csharp] [DllImport("Converter.dll")]rn static extern int CONV_FindConverter(ref ST_CONVINFO pstConvInfo, int iCount, int iTimeOut);rn [DllImport("Converter.dll")]rn static extern bool CONV_Init();rn rn public struct ST_CONVINFOrn rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]rn public string strMAC;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]rn public string strIP;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]rn public string strUserName;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]rn public string strDeviceName;rn rn rn private void button1_Click(object sender, EventArgs e)rn rn ST_CONVINFO st_=new ST_CONVINFO ();rn CONV_Init();rn CONV_FindConverter( ref st_ ,1,100);rn rn string stm = st_.strMAC;rn string stip=st_.strIP;rn [/code]rnrn当 st_ 返回为两个或两个以的结构数据就会出现以下错误 如果只返回一个结构数据就没有问题,大神们请指点下rn[img=https://img-bbs.csdn.net/upload/201405/29/1401353272_445964.jpg][/img]
C#调用非托管dll报错,尝试读取或写入受保护的内存,万分感谢
在delphi下能成功调用,声明如下:rnfunction Filter(m,n:integer;a1,a2:Array of double):double;stdcall; external 'LowFilter.dll';rnrnfunction TDataProcess.Velvet05Data(v1:double):double;rnvarrn a1,a2:Array of double;rn d1:double;rnbeginrn SetLength(a1,4);rn SetLength(a2,4);rnrn for i:=1 to 3 dorn beginrn a1[i] := i + 10;rn a2[i] := i * 10;rn end;rnrn [color=#FF0000]d1:=Filter(2,2,a1,a2);//能成功调用[/color]rn result:=d1;rnend;rnrnrn//*******************************************rn//C#下声明rn[DllImport("LowFilter.dll", EntryPoint = "Filter", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]rnpublic static extern double Filter(int m, int n, double[] a1, double[] a2);rnrnpublic double Velvet05Data(double v1)rnrn double d1;rn double[] a1, a2;rnrn a1 = new double[4];rn a2 = new double[4];rn for (i = 0; i <= 3; i++)rn rn a1[i] = i + 10;rn a2[i] = i * 10;rn rnrn [color=#FF0000]d1 = Filter(2, 2, a1, a2);[/color]//报错:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn return d1;rnrnrn由于该dll是已经封装好了,也无法看到源代码.也不知道采用什么语言编写.但能在delphi下成功调用.为什么在C#下用非托管方式却出错.rn看到网上有人说,要将该dll拷贝到system32下或debug下,但都还是报错!有知道的朋友帮助一下,万分感激!
C#动态调用C DLL时报错“尝试读取或写入受保护的内存”
各位好,在做程式调试时使用C打个了DLL包,定义如下。然后尝试在C#中做动态调用,代码编译通过,但是在执行时报错:"尝试读取或写入受保护的内存”rnrnDLL 打包时传入一个结构指针,传出一个结构指针。已经调试了几天,还是不知道问题在哪里。请各位多多帮忙!rn多谢!!!rnrn// C structure definernstruct PinDef rn int Slot; rn int Channel; rn char PinName[20];rn char PinType[5]; rn char DataType[5];;rnrnstruct PtnLst rn char PtnName[15]; rn int Load; ;rnrnstruct DCIn rn double VIH; rn double VIL; ;rnrnstruct DCOut rn double VOH;rn double VOL;;rnrnstruct DCInOut rn double VIH; rn double VIL; rn double VOH;rn double VOL;;rnrnstruct DPS rn char PwrPin[5];rn double Force; rn double Clamp;;rnrnstruct DCLevels rn char LevelName[15];rn struct DCIn DCLvlInput; rn struct DCOut DCLvlOutput;rn struct DCInOut DCLvlInOutput;rn struct DPS DCLvlDPS; ;rnrnstruct Period rn char Resource[15];rn double Value; ;rnrnstruct TDomain rn char TimingName[15];rn int SlotRef; rn double SlotDelay; rn struct Period Period; ;rnrnstruct Timing rn char TimingName[15]; rn struct TDomain TimingDomain; ;rnrnstruct DCTest rn char TestName[15]; rn char Exec[50]; rn struct Timing TimingBlk; rn struct DCLevels DCLevelsBlk;rn struct PtnLst Pattern; rn struct PinDef SigRefList[255]; rn char SignalRefStategy[20];rn double Force; rn double FRange; rn double MeaRange; rn double Delay; rn double Limits; rn double TimeOut; ;rnrnstruct TestResult rn int ErrCode;rn char ErrMsg[1024]; rn char PinName[5];rn char TestRslt[10];rn double TestVal;;rnrnrn// C DLL包接口定义rnvoid DummyTemplate2(struct DCTest* pRcvData, struct TestResult* ReturnData) rn double Value = 0.0; rn if ( !(strcmp (pRcvData->SigRefList[0].PinName, "DummyPin"))) rn strcpy(ReturnData->TestRslt,"Pass");rn Value = 2.0; rn else rn strcpy(ReturnData->TestRslt,"Fail");rn Value = 1.0; rn rn strcpy(ReturnData->PinName, pRcvData->SigRefList[0].PinName); rn ReturnData->TestVal = Value; rnrnrn// C# 结构定义rnusing System;rnusing System.Runtime.InteropServices;rnusing System.Collections.Generic;rnusing System.Linq;rnusing System.Text;rnrnnamespace Etidrnrn [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode,Pack = 1)]rn public struct PinDef rn public int Slot; rn public int Channel; rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]rn public string PinName;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]rn public string PinType; rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]rn public string DataType; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct PtnLst rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]rn public string PtnName;rn public int Load; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DCIn rn public double VIH; rn public double VIL; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DCOut rn public double VOH;rn public double VOL; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DCInOut rn public double VIH;rn public double VIL;rn public double VOH;rn public double VOL; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DPS rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]rn public string PwrPin; rn public double Force;rn public double Clamp; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DCLevels rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]rn public string LevelName;rn public DCIn DCLvlInput; rn public DCOut DCLvlOutput;rn public DCInOut DCLvlInOutput;rn public DPS DCLvlDPS; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct Period rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]rn public string Resource; rn public double Value; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct TDomain rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]rn public string TimingName; rn public int SlotRef; rn public double SlotDelay;rn public Period Period; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct Timing rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]rn public string TimingName; rn public TDomain TimingDomain; rnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct DCTest rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=15)]rn public string TestName;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=50)]rn public string Exec;rn public Timing TimingBlk;rn public DCLevels DCLevelsBlk;rn public PtnLst Pattern;rn [MarshalAs(UnmanagedType.ByValArray, SizeConst=255)]rn public PinDef[] SigRefList;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=20)]rn public string SignalRefStategy;rn public double Force;rn public double FRange;rn public double MeaRange;rn public double Delay;rn public double Limits;rn public double TimeOut; rnrn [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]rn public struct TestResult rn public int ErrCode;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=1024)]rn public string ErrMsg;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=5)]rn public string PinName;rn [MarshalAs(UnmanagedType.ByValTStr, SizeConst=10)]rn public string TestRslt; rn public double TestVal; rnrn public class TestDataContainer rnrnrn// -----------------------------------------------rn// C# 动态调用DLLrn// -----------------------------------------------rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Linq;rnusing System.Text;rnusing System.Windows.Forms;rnusing System.IO;rnusing System.Runtime.InteropServices;rnusing System.Xml;rnrnnamespace Etidrnrn public partial class ETID : Formrn rn public delegate void DummyTemplate2(ref DCTest DcEnv, ref TestResult NodeResult); rnrn DCTest nodeDcTestEnv = new DCTest();rn TestResult nodeTestRslt = new TestResult();rnrn // Initialize nodeDcTestEnvrn nodeDcTestEnv.TestName = ("DummyTest");rn nodeDcTestEnv.Exec = ("DummyTemplate2");rn nodeDcTestEnv.TimingBlk = new Timing();rn nodeDcTestEnv.TimingBlk.TimingName = ("SIM_Timing");rn nodeDcTestEnv.TimingBlk.TimingDomain = new TDomain();rn nodeDcTestEnv.TimingBlk.TimingDomain.Period = new Period();rn nodeDcTestEnv.TimingBlk.TimingDomain.TimingName = "DomainName";rn nodeDcTestEnv.TimingBlk.TimingDomain.SlotDelay = 1.0;rn nodeDcTestEnv.TimingBlk.TimingDomain.SlotRef = 5;rn nodeDcTestEnv.TimingBlk.TimingDomain.Period.Resource = "Internal";rn nodeDcTestEnv.TimingBlk.TimingDomain.Period.Value = 200;rnrn nodeDcTestEnv.DCLevelsBlk = new DCLevels();rn nodeDcTestEnv.DCLevelsBlk.DCLvlInput = new DCIn();rn nodeDcTestEnv.DCLevelsBlk.DCLvlInput.VIH = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlInput.VIL = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlOutput = new DCOut();rn nodeDcTestEnv.DCLevelsBlk.DCLvlOutput.VOH = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlOutput.VOL = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlInOutput = new DCInOut();rn nodeDcTestEnv.DCLevelsBlk.DCLvlInOutput.VIH = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlInOutput.VIL = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlInOutput.VOH = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlInOutput.VOL = 0.0;rnrn nodeDcTestEnv.DCLevelsBlk.DCLvlDPS = new DPS();rn nodeDcTestEnv.DCLevelsBlk.DCLvlDPS.PwrPin = "VCC";rn nodeDcTestEnv.DCLevelsBlk.DCLvlDPS.Force = 0.0;rn nodeDcTestEnv.DCLevelsBlk.DCLvlDPS.Clamp = 0.0;rn nodeDcTestEnv.DCLevelsBlk.LevelName = ("SIM_Levels");rn nodeDcTestEnv.Pattern = new PtnLst();rn nodeDcTestEnv.Pattern.PtnName = ("SIM_Pattern");rn nodeDcTestEnv.Pattern.Load = 0;rn nodeDcTestEnv.SigRefList = new PinDef[255];rnrn PinDef tmpSList = new PinDef();rn tmpSList.PinName = ("Du");rn tmpSList.Slot = 3;rn tmpSList.PinType = "In";rn tmpSList.Channel = 6;rn tmpSList.DataType = "WDT";rnrn for (int i = 0; i < 255; i++ )rn rn nodeDcTestEnv.SigRefList[i] = tmpSList;rn rnrn nodeDcTestEnv.SignalRefStategy = ("Single");rn nodeDcTestEnv.Force = 0.02;rn nodeDcTestEnv.FRange = 1.0;rn nodeDcTestEnv.MeaRange = 200.0;rn nodeDcTestEnv.Delay = 5.0;rn nodeDcTestEnv.Limits = 110.0;rn nodeDcTestEnv.TimeOut = 10.0;rnrn // Initialize nodeDcTestEnvrn nodeTestRslt.TestVal = 0.0;rn nodeTestRslt.ErrCode = 100;rn nodeTestRslt.PinName = "";rn nodeTestRslt.ErrMsg = "";rn nodeTestRslt.TestRslt = "";rn rn // 建立动态调用环境,都执行通过。 以下3行以说明为主。rn // string curDllPath = currentPath + "\\" + "DLL" + "\\" + "DummyTemplate2.dll";rn // DynamicLoadDLL dll = new DynamicLoadDLL(curDllPath);rn // DummyTemplate2 api = (DummyTemplate2)dll.Invoke("DummyTemplate2", typeof(DummyTemplate2));rn rn // 执行DLL, 执行下面一行时报错rn api(ref nodeDcTestEnv, ref nodeTestRslt); rn rnrnrn// -----------------------------------------------rn// 编译通过,下面是报错信息。rn// -----------------------------------------------rnMessage "尝试读取或写入受保护的内存。这通常指示其他内存已损坏。"rnStackTrace " rn在 Etid.ETID.DummyTemplate2.Invoke(DCTest& DcEnv, TestResult& NodeResult)\r\n rn
C# Marshal.PtrToStructure 尝试写入受保护的内存
结构内的string类型未给定长  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string str;
C#调用摄像头抓图时出现"尝试读取或写入受保护的内存..."
我们的程序是调用某专用摄像头的Activex控件来抓图,过程中程序会越来越慢,rn最后导致程序几乎死掉,报ex.Message = "尝试读取或写入受保护的内存。这通常指示其他内存已损坏。"rnrn检查程序发现该dispose的资源全都处理过了,暂时找不到解决问题的入手点,rn不知道针对这种内存在使用过程中占用越来越大的情况,有什么好办法处理,或者rn从哪几个方面去分析?rnrn求指教!!!
c#调用C++动态链接库出现尝试读取或写入受保护的内存
c++定义的动态库:rn[code=c]// 功能描述:获取测量值。rn// 输入参数:devID,设备编号;rn// channel,通道号,从 1~32;rn// pBuf Len, 数值缓冲区长度rn// 输出参数:pbDevIsRunning,设备运行状态,TRUE:运行,FALSE:停止rn// pTempVal,保存的采集值;rn// pBufLen,实际的采集数值点的数目rn// pChannelDistance,通道的是即距离,单位为m,该值为一个实际距离值的整数部分rn// pChannelPoints,通道的实际点数,该值为实际的点数值。rn//返 回 值:成功返回 1;失败返回负数; -1:获取失败rnDR_API int GetVal (int devID, unsigned char channel, bool *pbDevIsRunning, int* pChannelDistance, int* pChannelPoints, double* pTempVal, int* pBufLen);rn[/code]rnrn(功能描述:点击btnSetStartCollect后启动Timer,在Timer中循环调用GetVal获取测量值(pTempVal)。其中devID, channel已在调用其他函数后获取到,这里带入是有值的)rn在c#中的调用:rn[code=csharp]rn public static int devID; //在调用函数后 存储设备号devIDrn public static bool DeviceSatus; //在调用函数后 存储bDevIsRunningrnrn const int MAX_CHANNEL=4;rn //导入DLLrn[DllImport("DTSDS_Request.dll", EntryPoint = "GetVal", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]rnprivate static extern int GetVal(int devID, byte channel, ref bool pbDevIsRunning, int[] pChannelDistance, int[] pChannelPoints, double[] pTempVal, ref int pBufLen);rnrn private void Form1_Load(object sender, EventArgs e)rn rn RecieveTimer.Enabled = false;rn RecieveTimer.Interval = 1000; rn rnrn private void btnSetStartCollect_Click(object sender, EventArgs e)rn rn RecieveTimer.Enabled = true;rn // 功能描述:控制设备启动采集或停止采集rn // 输入参数:devID,设备编号;rn // bStart,TRUE 启动采集,FALSE 停止采集;rn // 返回值:成功返回TRUE;失败返回FALSE;rn bool inf = DTS_SetStartCollect(devID, true);rn labCurrentStatue.Text="返回值:\r\n" + inf +" TRUE 启动采集,FALSE 停止采集 ";rn RecieveTimer.Start();rn rnrn public static bool pbDevIsRunning;rnrn public static double[] pTempVal=new double[10000]; rnrn public static int[] ChannelDistance = new int[MAX_CHANNEL];rn public static int[] ChannelPoints = new int[MAX_CHANNEL];rn public static int pBufLen = 0;rn public static double[] CopyTempVal;rn public static double[] ReTempVal;rn //CopyTempVal = new double[pTempVal.Length]; ReTempVal = new double[pTempVal.Length]; 这两个数组在前面初始化设备的时候已经定义好长度,空间已申请rnrn private void RecieveTimer_Tick(object sender, EventArgs e)rn rn //读通道号rn byte channel = byte.Parse(textBox7.Text);rn //读数据rn int inf = GetVal(devID, channel,ref DeviceSatus, ChannelDistance, ChannelPoints, pTempVal, ref pBufLen);rn CopyTempVal = (double[])pTempVal.Clone();rn rn ReTempVal = new double[CopyTempVal.Length];rn int i = 0;rn foreach (double v in CopyTempVal)rn rn ReTempVal[i] = v + 1;rn i++;rn rn //画到chart上rn TempChart.Series[0].Points.DataBindY(CopyTempVal);rn TempChart.Series[1].Points.DataBindY(ReTempVal);rn [/code]rnrn可以在前几次调用GetVal后得到需要的pTempVal,在循环几次后timer回调的时候报错(10次内必报错),一般在下面地方报错(出现内存读写错误c0000005)rn[code=csharp] rn CopyTempVal = (double[])pTempVal.Clone();rn rn ReTempVal = new double[CopyTempVal.Length];rn int i = 0;rn foreach (double v in CopyTempVal)rn rn ReTempVal[i] = v + 1;rn i++;rn rn //画到chart上rn TempChart.Series[0].Points.DataBindY(CopyTempVal);rn TempChart.Series[1].Points.DataBindY(ReTempVal);[/code]rn我怀疑是自己类型转换出错,但是也没找到,c++的double*可以转为c#的double[]吧?每次单次读取就没什么问题,一旦放在timer里循环就报错。求各位大神帮看一下!!rn
C#调用dll中得回调函数出现“写入受保护的内存”
强帮忙看下这段代码是不是哪个数据类型我转换错了rn[code=C/C++]rn/**********************************vc++**********************************************/rntypedef struct VIDEO_INFOrnrn int nVideoWidth;/**< 像素宽度 */rn int nVideoHeight;/**< 像素高度 */rn int nVideoFPS;/**< 每秒多少帧 */rn unsigned char data[58];/**< 解码信息头 */rn DWORD dataSize;/**< 解码信息头长度 */rn struct timeval presentationTime;/**< 解码信息头时间戳 */rnVIDEO_INFO;rnrnrn/** @brief 报警信息结构体 */rntypedef struct MSG_INFO rnrn char ip[16];/**< 报警设备IP */rn long object_id;/**< 对象ID */rn long rule_name;/**< 参考枚举 Rule_name */rn long rule_id;/**< 规则ID */rn double rel_center_x;rn double rel_center_y;rn double rel_dimension_x;rn double rel_dimension_y;rn double rel_velocity_x;rn double rel_velocity_y;rn long preset_id;rn double direction;rn double time_in_rule;rn double range;rnMSG_INFO;rnrnrntypedef void (CALLBACK *MSGCallBack)(LONG lCommand,LONG nID,int nCh, char *pAlarmInfo, DWORD dwBufLen, void* Context);//报警回调函数rn/** rn* @brief 视频流回调函数rn* @param nStreamID 视频流的索引ID,AIIVS_OpenStream返回的rn* @param nID 设备索引ID,AIIVS_Connect返回的rn* @param nCh 设备的通道号rn* @param pBuffer 视频流帧数据rn* @param dwBufSize 帧数据长度rn* @param presentationTime 此帧时间戳rn* @param RealDataCallBackContext AIIVS_OpenStream时候 RealDataCallBackContext传进的值rn* @return 无返回值rn*/rntypedef void (CALLBACK *fRealDataCallBack) (LONG nStreamID,LONG nID, int nCh, const unsigned char *pBuffer, DWORD dwBufSize,struct timeval presentationTime, void* RealDataCallBackContext);//视频流回调rnrnAIIVS_API void __stdcall AIIVS_Init();//初始化SDKrnrnAIIVS_API LONG __stdcall AIIVS_Connect(char * sIp, int nPort , char * sName , char * sPwd ,MSGCallBack pMsgCallBack = NULL, void * Context = NULL); //连接IVS设备rnAIIVS_API int __stdcall AIIVS_OpenStream(LONG nID , int nCh,fRealDataCallBack pRealDataCallBack = NULL,void *RealDataCallBackContext = NULL);//开启视频流,返回通道流IDrnrnAIIVS_API int __stdcall AIIVS_GetHeadStream(LONG nID , int nCh,VIDEO_INFO *pVideoInfo);//获取视频流头部rnrnrnIVSPLAY_API BOOL _stdcall IVS_PLAY_Init();//初始化rnIVSPLAY_API LONG _stdcall IVS_PLAY_OpenStream(HWND hWnd,VIDEO_INFO *pVideo_info,bool bRealdecode = true);//打开流播放rnrn[/code]rn[code=C#]rn/*********************************C#*******************************************/rnrn public const string aiIvs = "AIIVS.dll";rn public delegate void MSGCallBack(long lCommand,long nID,int nCh, ref MSG_INFO pAlarmInfo,uint dwBufLen,ref int Context);rn public delegate void fRealDataCallBack(long nStreamID, long nID, int nCh, byte[] pBuffer, uint dwBufSize, timeval presentationTime,ref int RealDataCallBackContext);rnrnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct VIDEO_INFOrn rn public int nVideoWidth;//视频像素宽度rn public int nVideoHeight;//视频像素高度rn public int nVideoFPS;//视频每秒播放帧数rn public byte[] data;//解码头rn public int dataSize;//解码头长度rn public timeval presentationTime;//解码头时间戳rn rnrnrn [StructLayout(LayoutKind.Sequential, Pack = 1)]rn public struct MSG_INFOrn rn public string ip;/**报警设备IP */rn public long object_id;/**对象ID */rn public long rule_name;/**参考枚举 Rule_name */rn public long rule_id;/**规则ID */rn public double rel_center_x;rn public double rel_center_y;rn public double rel_dimension_x;rn public double rel_dimension_y;rn public double rel_velocity_x;rn public double rel_velocity_y;rn public long preset_id;rn public double direction;rn public double time_in_rule;rn public double range;rn rn public struct timevalrn rn public long tv_sec;rn public long tv_usec;rn rnrnrn [DllImport(aiIvs]rn public static extern void AIIVS_Init();rnrn [DllImport(aiIvs]rn public static extern long AIIVS_Connect(string sIp, int nPort , string sName , string sPwd ,MSGCallBack pMsgCallBack, ref int Context);rn [DllImport(aiIvs, EntryPoint = "_AIIVS_OpenStream@16")]rn public static extern int AIIVS_OpenStream(ref long nID ,ref int nCh,ref fRealDataCallBack pRealDataCallBack, ref int RealDataCallBackContext);//开启视频流,返回通道流IDrnrnrn public const string ivsPlay = "IVSPlay.dll";rn [DllImport(ivsPlay]rn public static extern bool IVS_PLAY_Init();rn [DllImport(ivsPlay]rn public static extern long IVS_PLAY_OpenStream(IntPtr hWnd,ref VIDEO_INFO pVideo_info, bool bRealdecode);rnrn public partial class frmVido : Formrn rn public frmVido()rn rn InitializeComponent();rn rn public int n_lUserID = -1;rn public int RealDataCallBackContext = -1;rn public IvsAPI.MSGCallBack MsgBack;rn public IvsAPI.fRealDataCallBack FrdcBack;rn private void frmVido_Load(object sender, EventArgs e)rn rn IvsAPI.AIIVS_Init();rn VIDEO_INFO video = new VIDEO_INFO();rn MsgBack = new IvsAPI.MSGCallBack(msgCallBack);rn FrdcBack = new IvsAPI.fRealDataCallBack(frcBack);rn int ibi = 0;rnrnrnrn long ll = IvsAPI.AIIVS_Connect("192.168.1.15", 80, "admin", "admin",MsgBack, ref n_lUserID);rn int ii = IvsAPI.AIIVS_OpenStream(ref ll, ref ibi,ref FrdcBack, ref RealDataCallBackContext);rn int it = IvsAPI.AIIVS_GetHeadStream(ll, 1, ref video);rn bool bolt = PlayAPI.IVS_PLAY_Init();rn long lon = PlayAPI.IVS_PLAY_OpenStream(pictureBox1.Handle, ref video, true);rn rn private void ListenAlarmThreadProc()rn rn rn private void msgCallBack(long lCommand, long nID, int nCh, ref MSG_INFO pAlarmInfo, uint dwBufLen, ref int Context)rn rn MessageBox.Show("成功");rn rn private void frcBack(long nStreamID, long nID, int nCh, byte[] pBuffer, uint dwBufSize, timeval presentationTime,ref int RealDataCallBackContext)rn rn bool bol1 = PlayAPI.IVS_PLAY_InputData(nStreamID, pBuffer, dwBufSize);rn rn rn[/code]
.NET3.5SP1 尝试读取或写入受保护的内存的问题补丁
.NET3.5SP1 尝试读取或写入受保护的内存的问题补丁。 微软官方补丁,仅供参考
【求助】尝试读取或写入受保护的内存。的问题
CookieContainer cookies = new CookieContainer();rn HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://175888.5d6d.com/logging.php?action=login&loginsubmit=yes&inajax=1");rn request.ContentType = "application/x-www-form-urlencoded";rn request.CookieContainer = cookies;rn request.AllowAutoRedirect = false;rn request.Headers.Add("Accept-Language: zh-CN");rn request.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";rn request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; staticlogin:product=cboxf2010&act=login&info=ZmlsZW5hbWU9UG93ZXJXb3JkMjAxME94Zl9VbHRpbWF0ZS5leGUmbWFjPTcyRjA0RUQxRDIzOTQzNUQ5NThEN0RCQzU0QjA1QjM0JnBhc3Nwb3J0PSZ2ZXJzaW9uPTIwMTAuNi4zLjYuMiZjcmFzaHR5cGU9MQ==&verify=6eeba67a2c6ecf5a12a3766ac2195a01; .NET4.0C; .NET4.0E; 360SE)";rn string postStr = "formhash=9d2a36b7&referer=http%3A%2F%2F175888.5d6d.com%2Fbbs.php&loginfield=username&username=wspyp24&password=wsfcdx01&questionid=0&answer=";rn byte[] data = Encoding.GetEncoding("gb2312").GetBytes(postStr);rn request.ContentLength = data.Length;rn request.Method = "POST";rn Stream stream = request.GetRequestStream();rn stream.Write(data, 0, data.Length);rn stream.Flush();rn HttpWebResponse response = (HttpWebResponse)request.GetResponse();rn是discuz论坛POST登录的程序,好像每次重启电脑后运行不会出异常,可是之后运行就会出异常 rnrn"尝试读取或写入受保护的内存。这通常指示其他内存已损坏。"rnrn但是我加了try catch也没有用,程序还是会被中断。rnrn而且开始异常是出现在CookieContainer cookies = new CookieContainer();rn我把这个注释掉后就变成了HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create抛异常。rn谁能告诉我是怎么回事啊?我查了出这个异常都是非托管资源没有被释放的问题。可是这里除了stream哪里有非托管资源啊?
相关热词 c# stream 复制 android c# c#监测窗口句柄 c# md5 引用 c# 判断tabtip 自己写个浏览器程序c# c# 字符串变成整数数组 c#语言编程写出一个方法 c# 转盘抽奖 c#选中treeview