我正在创建一个应该用作包装器的 C++/CLI DLL。它的目的是包装 C# SDK 并将函数呈现给 native C++ 代码。 我总是收到混合类型的错误,并且我在托管类中的 using 语句被标记为红色,所以这是我目前所拥有的:
#pragma once
#include <iostream>
#include <memory>
#include <string>
namespace TPInterface
{
class ITPFactory
{
public:
static __declspec(dllexport) std::shared_ptr<ITPFactory> CreateTPFactory();
};
}
它创建了一个 TPFactory 实例。
#pragma once
#include "ITPSSITotalStation.h"
#include "TPSSITotalStation.h"
#include "ITPFactory.h"
#include <iostream>
#include <memory>
#include <string>
namespace TPInterface
{
class TPFactory : public ITPFactory
{
public:
static std::shared_ptr<SensorSoftwareInterface::TotalStation::ITPSSITotalStation> CreateTPSSITotalStation(std::string pathToDriver);
};
}
这会创建一个 TPSSITotalStation 对象,它是一个 ITPSSITotalStation 接口(interface)。
TPSSITotalStation
-> TPSSIBase
-> TPSSBase
TPSSIBase
和TPBase
都包含用托管代码(ref 类)编写的类(gcroot 和 header )。
现在编译器告诉我,那些 ref 类是混合的,不允许等等。我不明白这里的问题...我做错了什么?
对不起,我是个笨蛋,我是 C++ 的新手,来自 C#。
错误:
Error 7 error C4368: cannot define 'm_selectedPath' as a member of managed 'TPInterface::Driver': mixed types are not supported
Error 8 error C4368: cannot define 'm_assemblyNameAndVersion' as a member of managed 'TPInterface::Driver': mixed types are not supported
Error 9 error C2678: binary '=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
Error 28 error C3265: cannot declare a managed '_Ptr' in an unmanaged 'std::tr1::_Ptr_base<_Ty>'
Error 51 error C3699: '*' : cannot use this indirection on type 'TPInterface::Sensor'
Error 65 error C3642: 'TPInterface::Sensor msclr::gcroot<T>::operator ->(void) const' : cannot call a function with __clrcall calling convention from native code
理解目的的小例子:
ref class Driver // Contains errors in using (C#) statements
{
// Does something managed
private:
std::string m_selectedPath;
std::string m_assemblyNameAndVersion;
}
ref class Sensor // Contains errors in using (C#) statements
{
// Does something managed
}
class TPBase
{
// includes Driver class and holds it also inside msclr::gcroot<Driver^>
}
class TPSSIBase : TPBase
{
// includes Sensor and Driver class and holds sensor also inside msclr::gcroot<Sensor^>
}
class TPSSITotalStation : TPSSIBase, public ITPSSITotalStation
{
// contains functions which should be exported to native C++
}
其余的已经在上面说明了。
最佳答案
- 您不能从托管类派生非托管类。
- 您不能从非托管类派生托管类。
- 您不能将托管成员添加到非托管类
- 不能向托管类添加非托管数据成员(指针除外)。
- 在非托管类中,您可以编写返回托管类型的函数。
- 在托管类中,您只能形成使用允许的托管类型的函数。
那么要做什么,创建一个包装器:
- 创建一个包含
gcroot<..>
的非托管类您需要创建和持有的所有托管对象的指针/对象。在文档中查找gcroot<..>
模板。 - 在托管类中,您可以自由持有指向非托管世界的指针。
只要您使用 gcroot 和普通指针,您就可以轻松地从非托管世界访问 .NET 世界,反之亦然。
关于c# - C++/CLI 混合托管/ native DLL 将无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420278/