3
votes

I've been using C# for a year, I know that you can access native code from C# via interop/PInvoke. I just started to learn DirectX and learned that one of the few ways to use DirectX with c# is by using something like SharpDX which is a wrapper written in c++ and not C#. my question is; since C# support interoperability and allow the programmer to access native dlls/com objects. how-come this support isn't valid when it comes to DirectX dlls/coms. I'm very confused

2

2 Answers

3
votes

This is not correct. SharpDX is a pure C# wrapper that is using some C++/CLI techniques through IL bytecode post-processing on the .NET assemblies. See the original post for more details. (In the section "How to avoid the usage of C++/CLI in C#"). For implementing a C++ interface callbacks in C#, you can have also a look at this post.

Even without the calli IL bytecode instruction, it would be perfectly possible to develop a full wrapper of COM objects using unmanaged delegates (through Marshal.GetFunctionPointerForDelegate). You can also do it with regular COM interop in C#.

On the other hand, if the C++ objects doesn't provide a COM interface (i.e only pure virtual methods) you will need a simplified C++ wrapper access for it or deal with the export mangling names for C++ objects (which is, afaik, not standardized)

2
votes

PInvoke is rather limited, and is applicable to C-style APIs, like Windows API. There are very small set of types, that could be marshaled.
Similar limitations exist for COM interop.

DirectX APIs are mostly C++ ones. You can't pass C++ class between boundaries - it's a headache. But C++/CLI is a way to go - it helps you to built some sort of bridge between managed and native world.