This post is written with help from many online resources and professional experience.
The main motivation behind using a C++ library for a C# code is code re-usability. I personally found it really hard to find a good resource on the net to create a C# project with C++ code.
Sample project – https://github.com/ashwinrs/TweetBank
Here are the steps involved in visual studio –
Adding the C++ project to VS-
First step is to get your C++ native code in to visual studio. File-> New -> Project -> Visual C++ -> Empty Project -> Ok . After this you can add existing code to your newly created project. In my code example the native C++ project is called “TweetBank”
- Right click the TweetBank project. Properties->General->ConfigurationType->StaticLibrary
- When you build it a lib directory will be created under “\TweetBank\Debug\TweetBank.lib”
Adding the CLR project to VS-
The CLR project acts like a bridge between your C++ code and C# code. File-> Add -> New Project -> Visual C++ -> CLR ->Empty Project
In my code example, the project and the class is named “TweetBankCLR”.
- Right click the TweetBankCLR project and click properties. C/C++->General->Additional Include Directories-> <Add TweetBankCore’s project directory>
- In properties go to Linker -> Input -> Additional Dependencies -> “TweetBank.lib”
- In propertied go to Linker -> general -> Additional Library Directories -> “E:\Apps\Dropbox\Code\vs\TweetBank\Debug”
- Right click the TweetBankCLR project. Properties->General->ConfigurationType->dll (This will create a DLL)
- Add reference to native project. Right click TweetBankCLR Add- > Reference -> Projects/solutions -> TweetBank
Adding the C# project to VS-
I will be creating a WPF project here. File-> Add -> New Project -> Visual C# -> Empty WPF Application. In my code example this project is named “TweetBankWPF”.
- Right click the TweetBankWPF and click “Set as Startup Project”
- Add reference to CLR project. Right click TweetBankWPF Add- > Reference -> Projects/solutions -> TweetBankCLR
- Right click and build TweetBankCLR. This should resolve any unresolved references from you C# code.
- Build TweetBankWPF. Tada!
More helpful links –
- http://stackoverflow.com/questions/19163839/how-to-access-class-in-c-cli-from-c
- http://stackoverflow.com/questions/10223186/c-cli-wrapper-for-native-c-to-use-as-reference-in-c-sharp
- For more info on how different data need to be exchanged between C# and C++ – http://www.codeproject.com/Articles/19354/Quick-C-CLI-Learn-C-CLI-in-less-than-minutes