Rella
Rella

Reputation: 66935

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?

Upvotes: 0

Views: 202

Answers (1)

Chris Vig
Chris Vig

Reputation: 8772

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.

Upvotes: 2

Related Questions