我正在爲一個非託管C++項目編寫一個使用C++/CLI的包裝庫。目標是將此庫展示給C#應用程序。這是迄今爲止我所擁有的。從Finalize中刪除一個非託管對象引發AccessViolationException
#pragma once
#include "Settings.h"
#include "Settings/SettingsPrivate.h"
public ref class Settings
{
public:
Settings();
virtual ~Settings();
protected:
!Settings();
public:
unsigned char GetModel(int iNumber);
private:
CSettings* m_pSettings;
};
#include "stdafx.h"
#include "Managed/Settings.h"
Settings::Settings()
{
// Pointer to unmanaged object
m_pSettings = new CSettings();
}
Settings::~Settings()
{
this->!Settings();
}
Settings::!Settings()
{
if (m_pSettings)
{
delete m_pSettings;
m_pSettings = NULL;
}
}
unsigned char Settings::GetModel(int iNumber)
{
return m_pSettingss->GetModel(iNumber);
}
的代碼執行測試應用程序,我寫的罰款。函數調用成功。問題是當GC完成這個對象時,它會拋出一個異常。
型「System.AccessViolationException」未處理的異常發生在Wrapper.dll
其他信息:試圖讀取或寫入保護內存。這通常表明其他內存已損壞。
我看不出任何明顯的原因,爲什麼拋出這個異常。我試圖通過從我的C#應用程序中調用Dispose來顯式地處理對象。它仍會拋出相同的異常。
這裏的測試應用程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WrapperTest
{
class Program
{
static void Main(string[] args)
{
Settings settings = new Settings();
byte b = settings.GetModel(0);
settings.Dispose();
return;
}
}
}
會有人指出我在做什麼錯?
沒有repro,看不到問題。我認爲問題出現在SettingsPrivate,我猜可能會造成堆損壞。 – 2011-04-01 01:06:04
如果您在調試器中啓用了第一次機會AV(「調試 - >異常 - > Win32異常 - >訪問衝突」;您可能想在「工具 - >選項 - >調試」中禁用「只是我的代碼」),什麼被訪問(你還需要在C#項目中啓用本地調試,因爲我假設你正在啓動它)?沒有什麼是跳出來的,因爲這段代碼錯了。 – 2011-04-01 02:52:34
@Hans:昨晚你的評論讓我走上正確的軌道來解決我的問題。如果你發佈了答案,我會給你這個問題的功勞。 – Nathanael 2011-04-01 15:51:29