Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ template function from C#

I have very limited knowledge of C#. My goal is to provide a C++ dll API to my C# co-worker. The dll has to be in C++ for legacy reasons.

Question - Can a C++ template function (shown below from VS) be marshaled in C#?

class  __declspec(dllexport) Foo
{
public: 
    template <typename T> T* getFoo(T* fooData){return fooData;};
};

If not, any suggestions? Should each type that is passed into the template function have their own function so C# can marshal it?

like image 263
LEO Avatar asked Oct 22 '25 04:10

LEO


1 Answers

Question - Can a C++ template function (shown below from VS) be marshaled in C#?

No. There is no compatible binary interface from C# to C++. You can only call exported C symbols from C#.

Theoretically, you could explicitly instantiate the templates in the C++ DLL, which will cause them to get external linkage and entries in the export symbol table. But name mangling will make the functions unusable for all practical purposes. The best way is therefore to have an intermediate C-compatible layer which calls the underlying C++ functions.

like image 190
Konrad Rudolph Avatar answered Oct 23 '25 20:10

Konrad Rudolph