managed c++ and c#

J

Jason

I am porting code from c++ and would like to use managed c++ to turn it into
an assembly for c#. The c++ code uses templates heavily ( via custom STL
containers ) and from what I read so does managed c++. How can I expose a
templated class for use in C#, or is it just an imposibility?

Jason
 
G

Guest

How can I expose a
templated class for use in C#, or is it just an imposibility?

This problem here is that templated types must be resolved at compile time. Templated types in assemblies are not possible and it just wont work.

I have attached some code which demostrates how you can consume a C++ dll from a C# but by putting template over the function it wont work.
// C++ dll
// cl /clr /LD template.cpp

using namespace System;
//template<typename T>
extern "C" __declspec(dllexport) void func(int value)
{
Console::WriteLine("Entering func");
}

// t.cs
// csc t.cs

using System;
using System.Runtime.InteropServices;

public class A
{

[DllImport("template.dll")]
// template<typename T>
static extern void func(int value);

static void Main()
{
func(1);
}
}
 
S

Steve McLellan

One thing you could do is (if possible) specialise the templates - if you're
only using them for a small number of types this might work. It wouldn't
entirely negate the point of templates, since you might have loads of
internal logic that you only need to write once. We've used this technique
when exposing a clas that coped with various bit-depths of image, for
example - wrote wrappers that exposed it for 1-, 8- and 16-bit images.
Obviously this sort of thing won't work if you're trying to expose bits of
the STL or more general code. In that case, you might be best off sticking
to managed C++.

Steve

kkhosla said:
This problem here is that templated types must be resolved at compile
time. Templated types in assemblies are not possible and it just wont work.
I have attached some code which demostrates how you can consume a C++ dll
from a C# but by putting template over the function it wont work.
// C++ dll
// cl /clr /LD template.cpp

using namespace System;
//template<typename T>
extern "C" __declspec(dllexport) void func(int value)
{
Console::WriteLine("Entering func");
}

// t.cs
// csc t.cs

using System;
using System.Runtime.InteropServices;

public class A
{

[DllImport("template.dll")]
// template<typename T>
static extern void func(int value);

static void Main()
{
func(1);
}
}


Jason said:
I am porting code from c++ and would like to use managed c++ to turn it into
an assembly for c#. The c++ code uses templates heavily ( via custom STL
containers ) and from what I read so does managed c++. How can I expose a
templated class for use in C#, or is it just an imposibility?

Jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top