Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to generate P/Invoke code?

Tags:

I am an experienced .Net programer, but have not compiled a C/C++ program in my life. Now I have this C-dll, headers and documentation (3rd party, not from Win API), from which I need to call about ten methods.

I was thinking of using Platform Invoke. I found these three tools that would create the code for me:

  • PInvoker: http://www.pinvoker.com
  • P/Invoke Interop Assistant: http://www.codeplex.com/clrinterop
  • P/Invoke Wizard: http://www.paulyao.com/res/pinvoke/pinvoke.aspx

and possibly

  • Swig: http://www.swig.org/

Pinvoker seems to have a bit different approach than the Interop assistant and the Wizard. Swig I just found when checking that this question has not been asked here.

What are the pros and cons of these tools?

What would be the best = easiest and safest way for me to produce the P/Invoke code given that I don't know much about C/C++?

like image 761
Ope Avatar asked Mar 22 '10 20:03

Ope


People also ask

How does P invoke work?

P/Invoke is the technique a programmer can use to access functions in these libraries. Calls to functions within these libraries occur by declaring the signature of the unmanaged function within managed code, which serves as the actual function that can be called like any other managed method.

What is PInvoke signature?

* The term PInvoke is derived from the phrase "Platform Invoke". PInvoke signatures are native method signatures, also known as Declare statements in VB.


1 Answers

See http://dotnetperls.com/dllimport-interop for an interop example, and this MSDN article for more info. The bible for this stuff is Adam Nathan's book.

Basically you will need to identify the functions in the DLL you want to call. These need to marked with extern to make them accessible to the outside world. The next step, which can get tricky is writing a DllImport for the function. This needs to map between the managed and unmanaged worlds. You will need to work out how to marshal any complex data structures from the C dll into managed code.

You should check to see if there is any sort of COM interface to the DLL. Make sure you really need to use P/Invoke first.

SWIG was originally for wrapping C/C++ code for use from scripting languages. It generates C# code from an interface description (see tutorial). I wouldn't recommend using it from C# if P/Invoke is an option.

like image 102
Brian Lyttle Avatar answered Oct 07 '22 19:10

Brian Lyttle