简体   繁体   中英

Return unmanaged object pointer in C#

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

  1. 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?

  2. 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

Solution from: Pass a C++/CLI wrapper of a native type to another C++/CLI assembly

// in WrapperB
property IntPtr _classB 
{
    IntPtr get() { return IntPtr(classB); }
}

// in WrapperA
ClassB *classB = static_cast<ClassB*>(wrapperB->_classB.ToPointer());
// ... do something ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM