简体   繁体   中英

Having a DLL with C++ class thats constructor takes in other C++ class, how to make C# capable of creating its instance?

My problem is quite simple: I have many DLLs with C++ classes that interfaces look like this:

// Boost
#include <boost/asio.hpp>
#include <boost/property_tree/ptree.hpp>

class service
{
public:
        virtual void service(boost::shared_ptr<boost::asio::ip::tcp::socket>, boost::property_tree::ptree) = 0;
};

I want to create tham from C#. How to do such thing?

You cannot directly create instances of native C++ classes in C#. The easiest thing to do would be to create a C++/CLI class that wraps the native class and exposes the members you need. You would have to provide the arguments to the underlying native class in your constructor, and figure out some type of scheme specifying the types of objects you want to pass to the native constructor.

ref class MyWrapperClass
{
public:

    MyWrapperClass() { m_native = new MyNativeClass( MyArgObj(), MyArgObj() ); }
    ~MyWrapperClass() { if( m_native ) delete m_native; m_native = NULL; }
    !MyWrapperClass() { if( m_native ) delete m_native; m_native = NULL; }

    void method1() { m_native->method1(); }
    int method2( int arg ) { return m_native->method2( arg ); }

private:
    MyNativeClass* m_native;
};

In C#, add a reference to the assembly with your wrapper class, and then you can use it as if it was an instance of the native class:

MyWrapperClass obj = new MyWrapperClass();
obj.method1();
int x = obj.method2( 15 );

It is tedious but not particularly difficult.

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