调用DLL的问题
大家好:
我用CLR封装了一个功能模块的DLL1,由于要转换成别人可以调用的数据格式,我在功能模块DLL1上又封装了一个DLL2,
现在在测试程序在调用的时候,回调函数都能执行到,就是在跳出回调函数时
提示未处理的“System.AccessViolationException”类型的异常出现在 clidll.dll 中。
其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
如果不做成DLL直接调用的话,程序是正常的.
我做了个测试程序 大家帮忙分析下 本人万分着急
第一层DLL的程序如下:
#pragma once
#ifdef EMUAPI_EXPORTS
#define EMUNAPI_API __declspec(dllimport)
#else
#define EMUAPI_API __declspec(dllexport)
#endif
//emu.h
typedef void (*callbackEmu) (int cause);
namespace emuterminal {
class EMUAPI_API emu
{
public:
emu(void);
public:
~emu(void);
public:
void setcallback(callbackEmu callb); //让调用者传一个函数指针进来
void test(int i); //在该函数中调用回调函数
public:
callbackEmu m_CallbackEmu;
};
}
//emu.cpp
#include "StdAfx.h"
#include "emu.h"
#include <ostream>
namespace emuterminal {
emu::emu(void)
{
}
emu::~emu(void)
{
}
void emu::test(int i)
{
this->m_CallbackEmu(i);
printf("i = %d\n",i);
}
void emu::setcallback(callbackEmu ca)
{
this->m_CallbackEmu = ca;
}
}
在上面第一层DLL上再封装一层DLL程序如下:
//clidll
// clidll.h
#pragma once
#include "emu.h"
#define EMUAPI_EXPORTS
//#ifdef CLIAPI_EXPORTS
//#define CLINAPI_API __clrcall(dllimport)
//#else
//#define CLIAPI_API __clrcall(dllexport)
//#endif
using namespace System::Runtime::InteropServices;
using namespace System;
namespace clidll {
public delegate void CallBackDelegate( int cause);
[StructLayoutAttribute( LayoutKind::Sequential, CharSet = CharSet::Ansi )]
public ref struct Managed_Delegate_Wrapper
{
[MarshalAsAttribute(UnmanagedType::FunctionPtr)]
CallBackDelegate^ _Delegate;
};
public ref class emumodule
{
// TODO: 在此处添加此类的方法。
public:
emumodule():m_Impl(new emuterminal::emu)
{
//m_Impl = new emuterminal::emu();
_Status_Delegate = gcnew Managed_Delegate_Wrapper();
_Status_Delegate->_Delegate =
gcnew clidll::CallBackDelegate(this, &emumodule::ActualMethodInWrapper);
callbackEmu callback;
Marshal::StructureToPtr (_Status_Delegate, (System::IntPtr)&callback, false);
m_Impl->setcallback(callback);
}
~emumodule()
{
delete m_Impl;
}
public:
void test(int i)
{
m_Impl->test(i);
}
public:
emuterminal::emu* m_Impl;
Managed_Delegate_Wrapper^ _Status_Delegate;
void ActualMethodInWrapper(int i)
{
System::Console::Write("callbace: " + i.ToString());
System::Console::Write("\n" );
}
};
}
// clidll.cpp
#include "stdafx.h"
#include "clidll.h"
namespace clidll {
}
// 测试程序入口
// ClrT.cpp: 主项目文件。
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
::clidll::emumodule^ l = gcnew clidll::emumodule();
while(true)
{
l->test(1);
}
Console::WriteLine(L"Hello World");
return 0;
}
如果要调试的话 本人打包(文件很小)发给你 你在机子上运行即可调试 本人QQ:54869575
期待有心人提供帮助 在下感激不尽