Tuesday, March 1, 2011

Wrapping Visual C++ in C#

I need to do some process injection using C++ but I would prefer to use C# for everything other than the low level stuff. I have heard about "function wrapping" and "marshaling" and have done quite a bit of google searching and have found bits of information here and there but I am still really lacking.

Things I have read in order of usefulness;
http://msdn.microsoft.com/en-us/library/ms235281(VS.80).aspx
http://www.drdobbs.com/cpp/184401742
http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html

How can I wrap all the lower level stuff (native C++) in C# so I can easily command those functions in a language I am more comfortable with, C#?

Any information on the topic is much appreciated.

From stackoverflow
  • You want to use P/Invoke, see MSDN Magazine.

    Marcus Cicero : The only thing is that I am not trying to call any windows API function. I want to inject into a 3rd party process, and call certain functions in that process using asm/etc via native C functions that I can call from say C#. Maybe I am misunderstanding the article however. Thanks.
  • If Pinvoking isn't what you want to do, then create a managed C++ application. Use native C++ to do the process injection stuff. Use managed c++ to create a .NET friendly interface to this native behaviour. This can then be called from C#.

    Marcus Cicero : Any guides or examples you could point me to? Thanks!
  • I think P/Invoke is really the most straightforward approach:

    • Create a DLL in unmanaged C++, containing all the functionality you need to do the injection.
    • In your C# code, declare some static extern methods, and use the DllImport attribute to point them to your C++ dll. For more details, see the link provided by arul in his answer.

    Note that P/Invoke isn't limited to "windows API functions" — you can call functions exposed by any native DLL.

    A potential downside of P/Invoke is that you will have to provide the signatures for your C++ functions, possibly specifying some less-than-obvious marshalling. In that case, you could consider constructing a COM server instead of a "plain" DLL, and using COM interop to call your code from C#.

    Marcus Cicero : Thank you for the clarification.

0 comments:

Post a Comment