Question

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.

Was it helpful?

Solution

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#.

OTHER TIPS

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

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#.

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