P / Invoke C ++ template <T> from C #

I defined in C ++ a function for external calls:

template<typename T> void __declspec(dllexport) SwapMe(T *fisrt, T *second) { std::cout << typeid(T).name() << std::endl; T temp = *first; *first = *second; *second = temp; } 

I want to use it in a C # program. I tried this way:

 unsafe class Program { [DllImport("lib1.dll", EntryPoint = "SwapMe")] static extern void SwapMe<T>(T first, T second); ... } 

But I get this error:

A common method or method in a generic class is an internal call, PInvoke, or defined in a COM import class.

It seems that Generic in C # is type-driven, and these are quite different things in architecture with an unmanaged template in C ++.

How can I use the template method in my C # program?

+7
source share
2 answers

Template functions are not burned in binary format by the C ++ compiler. Occasionally, only specialized versions are available. The C ++ compiler logically clones the definition of the template and replaces T any specific type.

This means that you must create a specialized shell:

 void __declspec(dllexport) SwapMe(int *fisrt, int *second) { //example { SwapMe(first, second); } 

You can call this from C #, but you cannot call the version of the template.

C ++ templates and C # generators work differently.

+8
source

To add to the above, we recently went through this and used T4 (TextTransform.exe) to create templates for wrappers in C ++.

To do this, we included the T4 file in the C ++ project, and for each combination of args types we generated a wrapper method around the C ++ template. Then the wrapper method was unloaded.

Finally, in C # we did the same, using T4 to create a common wrapper around the exported methods. This way you bridge the gap between .NET Generics and C ++ templates using all the features of C ++ Templates

0
source

All Articles