在c#中继承原生c++,并将继承类向后传递给c++
Inheriting from native C++ in C# and passing the inherit class backward to c++
我在本地c++ dll中有一个引擎,我需要在c#项目中使用它。
我完全是新手,但我已经在谷歌上搜索了几个小时,现在我或多或少知道如何实现它。我知道我必须写一个c#或c++/CLI包装类。但是我还没有找到如何包装一些方面的dll c++类。这个引擎有一个CEntity类,它有这个重要的部分:
class CEntity
{
void SendMsg(CEntity *receiver);
virtual void ReceiveMsg(MSG msg);
}
的工作原理如下:来自CEntity的继承类覆盖了ReceiveMsg函数,实现了它想要的东西,继承对象通信发送消息。
我需要的是在c#中使用这个功能:从CEntity"继承",以c++代码可以调用的方式重写ReceiveMsg,并能够向其他c#"继承"CEntity对象发送消息,抛出SendMsg c++实现。换句话说,我需要c++非托管代码调用c#托管代码。c++代码正在调用ReceiveMessage(),我需要"重写"它或将该调用重定向到c#代码中。
是一种不改变dll的方法吗?我不能直接访问c++代码,但如果需要,我可以要求修改dll。如果没有,最小的dll修改是多少?
Thanks to lot
这很棘手:
ILogger.h
#pragma once
using namespace System;
namespace AlPDFGenV4
{
public interface class ILogger
{
public:
virtual void Log( String^ ltxt ) = 0;
};
}
然后LRLog.h
#pragma once
#include "CMSysString.h"
#include "CLRILogger.h"
#include <vcclr.h>
using namespace System;
class CNtvLogger;
namespace AlPDFGenV4
{
public ref class Logger
{
public:
Logger(void);
virtual ~Logger(void);
ILogger^ extlogger;
CNtvLogger *ntv;
void Log( String^ txt )
{
extlogger->Log( txt );
}
};
}
和LRLog.cpp
#include "StdAfx.h"
#include "LRLog.h"
using namespace AlPDFGenV4;
Logger::Logger(void)
{
ntv = new CNtvLogger;
ntv->clrlogger = this;
}
Logger::~Logger(void)
{
delete ntv;
}
class CNtvLogger : CMSysLogger
{
public:
gcroot<AlPDFGenV4::Logger ^> clrlogger;
protected:
void _InternalLog( LPCTSTR txt)
{
String ^str = gcnew String( txt );
clrlogger->Log( str );
}
public:
bool Init(void * obj)
{
return true;
}
};
希望对你有帮助。
在本例中,类Logger是一个桥接器,它允许在本机日志记录器(由本机代码使用)和接口ILogger(由托管代码使用,用于传递接收日志输出的类)之间保持链接。
在c++/CLI中需要这样的类,不需要用这种方法更改dll
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象