This tutorial step by step instructions to expose .lib files or access native functions from a managed application using a wrapper dll.
Create the C/C++ wrapper DLL:
- Create a Win32 project in Visual Studio 2010 and name it DemoLib.
- Select DLL in application type
- Check Export symbols in additional options.
- In DemoLib.h: modify #define, add the function fnDemoLibAdd(int a, int b) and remove all the other declarations.
#define DEMOLIB_API extern "C" __declspec(dllexport) DEMOLIB_API int fnDemoLibAdd(int a, int b);
- In DemoLib.cpp, add the following definition:
DEMOLIB_API int fnDemoLibAdd(int a, int b) { return (a+b); }
- To specify include directories:
Right-click on the Demolib project and select Configuration Properties, C/C++ and then General. In Additional Include Directories: Click edit and add the directory - To include *.lib files:
Right-click on the Demolib project and select Configuration Properties, Linker and then Input. In Additional Dependencies: Click edit and add the library(*.lib) file - To change the output directory:
Right-click on the Demolib project and select Configuration Properties and then General. In Output Directory: Click edit and specify the directory preferably with macros - Build the project, the DemoLib.dll will be in the default output directory: Debug/Release or in the directory specified above.
- Create a .NET 4 Visual C# project in Visual Studio 2010
- Add DemoLib.dll ceated above to the project and select the “Copy to Output Directory” as “Copy if newer”
- Add the function definitions using DllImport
[DllImport("DemoLib.dll")] public static extern int fnDemoLibAdd(int a, int b)
- Function fnDemoLibAdd() can be called from within c# now.
<configuration> <runtime> <NetFx40_PInvokeStackResilience enabled="1"/> </runtime> </configuration>
References: Calling a C++ lib from C#