2

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

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
g.pickardou
  • 32,346
  • 36
  • 123
  • 268
  • Does this answer your question? [Is there a tool that generates P/Invoke signatures for arbitrary unmanaged DLL?](https://stackoverflow.com/questions/6319650/is-there-a-tool-that-generates-p-invoke-signatures-for-arbitrary-unmanaged-dll) – StayOnTarget Jun 28 '21 at 20:38

1 Answers1

2

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 2
    David wrote "...There are tools that can help...". I understood the limitations. What are the tools... :-)? – g.pickardou Mar 25 '14 at 12:13
  • For instance: http://stackoverflow.com/questions/2495632/easiest-way-to-generate-p-invoke-code but personally I've never used any of these and am exceedingly sceptical of their value. I would always write my own p/invokes. – David Heffernan Mar 25 '14 at 12:19