简体   繁体   中英

Initialize a reference to a C# shared pointer from C++ using SWIG

I'm trying to initialize, in C++, a reference to a boost shared pointer passed from C#, while trying to maintain the inheritance tree. I want to be able to create a variable in C# then pass it to my DLL which will instantiate it internally (so that I can manage all memory allocation in the same context).

Here's my C++ test case (in file SwigTest.h) :

#include <string>
#include <boost/shared_ptr.hpp>

template<class T>
using SRef = boost::shared_ptr<T>;

class FactoryClass
{
   public:
      FactoryClass() {}
      ~FactoryClass() {}

      //Normally I would only like to use the return value, but SWIG uses polymorphism to simulate templates
      //and polymorphism on the return type only is not supported by C#. (I get a Identifier 'getReference' redefined error on SwigTest.i compilation).
      //So I thought I’d pass the SRef& as a parameter instead of having no parameters at all.
       template <class  T>
       static SRef<T> getReference( SRef<T>& inout ) { inout = SRef<T>( new T(1) ); return inout; }

       void testing( int& toto ) {};
};

class BaseClass
{
   public:
      BaseClass() { m_flag = -1; };
      BaseClass(int i) { m_flag = i; };
      virtual ~BaseClass() {};

      virtual std::string getName() = 0;

      int m_flag;
};

class FirstClass : public BaseClass
{
   public:
      FirstClass() {};
      FirstClass(int i) : BaseClass( i ) {};
      virtual ~FirstClass() {};

      virtual std::string getName() { return "First Class"; };
};

class SecondClass : public BaseClass
{
   public:
      SecondClass() {};
      SecondClass(int i) : BaseClass( i ) {};
      virtual ~SecondClass() {};

      virtual std::string getName() { return "Second Class"; };
};

Here's my current SWIG interface file :

%module SwigTest
%include "std_string.i"
%include "boost_shared_ptr.i"

%{
#include "../include/SwigTest.h"
%}

%shared_ptr( BaseClass );
%shared_ptr( FirstClass );
%shared_ptr( SecondClass );

%include "../include/SwigTest.h"

%template(BoostBasePtr) boost::shared_ptr<BaseClass>;
%template(SharedBase) SRef<BaseClass>;

%template(BoostFirstPtr) boost::shared_ptr<FirstClass>;
%template(SharedFirst)SRef<FirstClass>;
%template(getReference)FactoryClass::getReference<FirstClass>;

%template(BoostSecondPtr) boost::shared_ptr<SecondClass>;
%template(SharedSecond)SRef<SecondClass>;
%template(getReference)FactoryClass::getReference<SecondClass>;

And here's what works and doesn't in C# :

public class SwigInterface
{
   private FirstClass m_first;
   private SecondClass m_second = new SecondClass(-2);

   void TestSwig ()
   {
      m_first = FactoryClass.getReference( m_first ); //The returned reference is copied from C++
      FactoryClass.getReference( m_second ); //m_second is never changed

      FirstClass anotherFirst = new FirstClass(-1) ;
      BaseClass bc = FactoryClass.getReference( anotherFirst); //bc does equal the new instance of FirstClass but anotherFirst is not correctly replaced

       //This is the case I would ideally want to use
       SecondClass nothing ;
       FactoryClass.getReference( nothing ) ; //NullReferenceException (because the SWIG generated interface uses nothing.CPtr() to pass by pointer as it does with all refs).
    }
}

I tried a lot of %typename gymnastics to replace the signature of FactoryClass.getReference( FirstClass ) with FactoryClass.getReference( out FirstClass ) (or even ref FirstClass) but I can't find a way to do it properly.

In a perfect world, I would just like to generate a void getReference<T>( ref T inout ) in my FactoryClass in C#, but even adding the method using the SWIG %extend keyword doesn't generate it because I have to instantiate every template I need.

If I understand your point, you have reached a SWIG limit. I have faced the same issue. Each pointer (smart or not) loses polymorphism once in C#.

You need to provide a special factory for your BaseClass in the C# side, using %pragma(csharp) directive. Then you need to map your pointer with a csout typemap like this:

%typemap(csout, excode=SWIGEXCODE)
  BaseClass*, std::shared_ptr<BaseClass>, std::shared_ptr<BaseClass> & {
    System.IntPtr cPtr = $imcall;
    // The following line is a call to your special factory
    BaseClass ret = $imclassname.createBaseClass(cPtr, $owner);$excode
    return ret;
}

Your factory could be something like this:

%pragma(csharp) imclasscode=%{
    public static BaseClass createBaseClass(System.IntPtr cPtr, bool owner)
    {
        BaseClass ret = null;
        if (cPtr == System.IntPtr.Zero) {
          return ret;
        }
        string name = ($imclassname.BaseClass_getName(new System.Runtime.InteropServices.HandleRef(null, cPtr)));
        switch (name)
        {
        case "First Class":
            return new FirstClass(cPtr, owner);
        case "Second Class":
            return new SecondClass(cPtr, owner);
        default:
            return null;
        }
    }
%}

I didn't test it, maybe there are some things to change or adapt. But it should work.

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