返回 C# 中的非托管对象指针
我已经为本机 C++ 类编写了两个托管 C++ 包装器,并且我需要本机类 B 的非托管对象作为构造本机类 A 的托管包装器 A 函数中的返回参数!
示例:
// Wrapper A
WrapperA::WrapperA(ClassB *classB)
{
ClassA *classA = new ClassA(classB);
...
}
// native c++
ClassA::ClassA(ClassB *classB)
{
m_classB = classB; // ClassB *m_classB; in .h
...
}
// Wrapper B
ClassB* WrapperB::GetNativeClassB()
{
return m_classB; // ClassB *m_classB; in .h
}
// in C#
...
WrapperB wrapperB = new WrapperB();
unsafe // need for C++ pointer
{
WrapperA wrapperA = new WrapperA(wrapperB.GetNativeClassB() );
// Error: is inaccessible due to its protection level
// -> is set to public
}
...
是否有更好的方法而不不安全以及为什么我收到访问错误???
先感谢您!
问候莱昂22
I have written two managed C++ wrappers for native C++ classes and I need a unmanaged object of native Class B as a return param in function of managed Wrapper A that construct native Class A!
Example:
// Wrapper A
WrapperA::WrapperA(ClassB *classB)
{
ClassA *classA = new ClassA(classB);
...
}
// native c++
ClassA::ClassA(ClassB *classB)
{
m_classB = classB; // ClassB *m_classB; in .h
...
}
// Wrapper B
ClassB* WrapperB::GetNativeClassB()
{
return m_classB; // ClassB *m_classB; in .h
}
// in C#
...
WrapperB wrapperB = new WrapperB();
unsafe // need for C++ pointer
{
WrapperA wrapperA = new WrapperA(wrapperB.GetNativeClassB() );
// Error: is inaccessible due to its protection level
// -> is set to public
}
...
Is there a better way without unsafe and why I get an access error ???
Thank you in advance!
greets leon22
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
保护级别:我确定您已公开定义,但是包含该符号的 dll 又如何呢?您确定您拥有最新版本吗?
不安全:为了使用/包装不安全/本机代码作为 C++,最好的选择是使用 C++/CLI(前托管 C++),从 Visual Studio 开始提供2005 年发布。只需定义一个包装您的本机/非托管类的引用类,该类就可以像 C# 一样从托管代码中直接访问。使用 Visual Studio 启动的提示:从 Visual C++ 部分打开一个新的 dll CLR 项目;
我认为 C++/CLI 是最好的解决方案
Protection level: i'm sure you have public defined, but what about the dll containing the symbol? Are you sure you have the last release?
Unsafe: in order to use/wrap unsafe/native code as C++, the best option it is to use C++/CLI (ex Managed C++), provided starting from the Visual Studio 2005 release. just define a ref class that wraps your native/unmanaged class, that one will be directly accessible from managed code, as C#. Hint to start with Visual Studio: open a new dll CLR project from the Visual C++ section;
C++/CLI is the best solution in my opinion
解决方案来自: 传递 C++ /CLI 将本机类型包装到另一个 C++/CLI 程序集
Solution from: Pass a C++/CLI wrapper of a native type to another C++/CLI assembly