expose c++/CLI templated wrapper to c#

≡放荡痞女 提交于 2019-12-06 16:27:54

As you have seen, managed templates aren't accessible outside of the assembly where they are located. Basically the idea is to expose the managed template as a generic interface which can be sent across assembly boundaries.

So in your case you would want to create a ITestTemp, something like this...

generic<typename T> public interface class ITestTemp
{
  public:
    TestTemp(T val);
}

That is the interface that you will export across assemblies. Now you will have to convert your managed template into that generic interface to do so you can use inheritance, something with the following signature (internals omitted for simplicity)

templace<typename T> ref class TestTemp : ITestTemp<T>

Once you have that now you will have to do the "compiler's work" (what is normally just automagically handled for a regular C++ template) for it to convert between the two so to speak. So you will have to create a factory method that will create the specific instances that you are looking for. It would look like this

public ref class TestTempFactory
{
  public:
    generic<typename T> static ITestTemp<T>^ Create()
    {
      if (T::typeid == String::typeid)
      { return (ITestTemp<T>^) gcnew TestTemp<String>(); }
      //more cases as needed...
    }
}

I hope that explains it well enough, if not let me know.

If you implement a full-fledged subclass of your template class, that should do the trick. You will need to implement all the constructors, but just as a pass-through to the base class's constructors; no actual code.

public ref class TestTempFloat : TestTemp<float>
{
    TestTempFloat(float val) : TestTemp(val) { };
};

If you have a lot of these, you could make use of the preprocessor:

#define IMPLEMENT_TESTTEMP(namesuffix, type) \
public ref class TestTemp ## namesuffix : TestTemp<type> \
{ \
    TestTemp ## namesuffix(type val) : TestTemp(val) { }; \
};

IMPLEMENT_TESTTEMP(Float, float)
IMPLEMENT_TESTTEMP(Double, double)
IMPLEMENT_TESTTEMP(Int, int)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!