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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With