So our customer's goal was to update their native C++ application with support for calling a static instance of a C# class and share that instance with native and managed clients from within the same process space. This is a sample created to demonstrate one method to accomplish this task. (Many thanks to Rodney Viana for helping solve several critical problems I ran into making this sample work (if you have not downloaded Rodney's debugging extension - what are you waiting for? http://netext.codeplex.com/)
We chose a mixed C++/CLI adapter as a solution:
Visual C++ supports the use of the Standard C++ Library, the Common RunTime library (CRT), ATL, and MFC for applications compiled with /clr (Common Language Runtime Compilation). This allows existing applications that use these libraries to use .NET Framework features as well. From <https://msdn.microsoft.com/en-us/library/ms173268.aspx>
Solution contains three projects (Link to Visual Studio Solution: http://1drv.ms/1A45F7Q):
- shared_object - C# Class project (.Net 4.5.1)
- mixedAdapter - C++ CLR project
- client - C++ Win32
This DLL exposes a simple singleton class with one method named Hello_World. It returns a string to the caller.
This is the C++ CLR project which acts as an adapter or wrapper. It can been called from C++ natively and it can add managed references. I have a project reference to shared_object. Make sure to add this to your class __declspec(dllexport) so your client project can import later:
Client has a header file with __declspec(dllimport) to import the definition from the lib file
And the client.cpp file has #pragma comment (lib,"mixedAdapter") added which is a hint to the linker to find the correct lib file. To get this working, I opened to project properties of client, under Linker, I selected "Additional Library Directories" and put in the path of my mixedAdapter.lib file. Without this step you may get a complier error.
C:\Visual Studio 2013\Projects\mixedAdapter\Debug>client.exe