Search code examples
.netc++-clipinvoke

How to use C++ code from C#?


I need to use this library (Interception). It is written in C++. Briefly, it lets you manipulate input from keyboard or mouse. What I need to do is to use some of those calls from C#.

I'm not sure which path to follow. So far I've read that you could use Pinvoke to use C++ code inside C#.

I have many questions regarding PInvoke:
1) Do Pinvoke libraries need to be in a specific system path to be found (e.g. system32)?

I've read that getting the right PInvoke signatures can be hard and error prone, and since I couldn't find any PInvoke signature for Interception in PInvoke.net,
2) Does that mean that I should desist on using PInvoke?

I've also seen, but didn't go much into detail, that in Visual Studio, when you create a project, you can create a Visual C++->CLR->Class Library.
3) Should I use this to build an assembly linking Interception? Could this assembly be used within C#?

Anyways, if a C# alternative to Interception exists, I would use that instead.


Solution

  • 1) No, if the library is in the same path as the executable, it will work.

    2) You only use PInvoke with C functions, not C++ objects. So using PInvoke to directly call Interception library is probably out of the question.

    3) You can create a C++/CLI library that links to Interception. But you will have to create your own .NET objects to wrap the pure C++ objects in Interception.

    I would recommend you read a bit about coding CLR in C++. Making a CLR wrapper in C++/CLI is probably the cleanest way to go.