Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have defined in C++ 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 C# program. I've tried in this way:

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

    ...
}

But, I'm getting such error:

Generic method or method in generic class is internal call, PInvoke, or is defined in a COM Import class.

Seems to be, that Generic in C# is managed type and it's rather different stuff by architecture with unmanaged template in C++.

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

like image 354
Secret Avatar asked Dec 29 '12 18:12

Secret


1 Answers

Template functions are not burnt into the binary by the C++ compiler. Only specialized versions are ever emitted. The C++ compiler logically clones the template definition and replaces T with whatever concrete type is wanted.

This means that you must create a specialized wrapper:

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

You can call this one from C#, But you cannot call the template version.

C++ templates and C# generics work very differently.

like image 117
usr Avatar answered Sep 18 '22 19:09

usr