C ++ template function call from C #

I have very limited knowledge of C #. My goal is to provide a C ++ dll API to my C # employee. Dll should be in C ++ for reasons deprecated.

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

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

If not, any suggestions? If each type that is passed to the template function has its own function, why can C # marshal it?

+3
source share
3 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 characters from C #.

, ++ DLL, . . - , ++.

+4

, ++/CLI. API, #, ++.

+4

, - , , . (Pardon the Pseudo code Appearance). # ++/CLI.

. ++- ( VS) #?

: # ++, .

:

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

extern "C" __declspec(dllexport) void call_getFoo(Foo* pFoo, void* pfooData, int fooId)
{
    switch(fooId)
    {
        case(ENUM::1) : //Use an enum here for a better switch statement.       
        {   
            //Cast the void pointer to a specific type so the template knows how to use it.
            pFoo->getFoo((*TypeCast*)pfooData);
        break;
        }
    }
}

//C# Code
internal static class UnsafeNativeMethods
{
    const string _dllLocation = "Foo.dll";

    [DllImport(_dllLocation)]
    static public extern void call_getFoo(IntPtr pFoo, IntPtr pfooData, int fooId);           
}

//In a C# method
...
...
//Marshal Up a C# data type to a pointer for C++.
*YOUR TYPE HERE* myType;
int rawsize = Marshal.SizeOf(myType);
IntPtr pfooData = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(myType,pfooData,true);

//call the C++ dll
UnsafeNativeMethods.call_getFoo(pFoo, pfooData, fooId);

//Convert Ptr Back To myType
myType = (*YOUR TYPE HERE*) Marshal.PtrToStructure(pfooData, typeof(*YOUR TYPE HERE*));
...
...

, !

+1

All Articles