Question

Suppose I have a dll written in pure C. I have an inculde file (.h) so I can use the dll from a VS 2012 C project.

Is there any way to generate a C# wrapper class based on the metainfo in the include file, or I must write all the [DllImport]... manually? The C source code for dll is also available.

(Please note: This is not a COM library)

Thanks in advance

Was it helpful?

Solution

There are tools that can help, but by and large you have to write the wrapper code yourself to some degree. The main reason being that a C header file does not fully specify the interface. For instance, consider this function:

void foo(int* x);

Does this function receive a pointer to a single int, or does it receive a pointer to an array? There's no way for you to tell with just this information. So, any tool that creates wrappers must also use some form of annotation to fully describe the semantics of the functions. If those annotations are not present you would need to create them. At which point it probably becomes quicker and easier to write the wrapper manually.

As an alternative to writing C# pinvokes you can use a mixed mode C++/CLI assembly. This can include the header file and link against the import library. Then all you need to do is write a C++/CLI ref class to wrap the interface, and add the C++/CLI assembly as a reference to your C# project.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top