Click here to Skip to main content
15,917,862 members
Articles / Desktop Programming / MFC

Consuming Your C# Library in MFC/C++ Project

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
11 Apr 2023MIT3 min read 11.6K   249   14   7
Consuming Your C# Library in MFC/C++ Project via C++/CLI

The code is hosted on Github.

This article serves as a reference to using your .NET C# library in a native C++ project via C++/CLI in Visual Studio 2022. You can follow even if you are using earlier Visual Studio because the steps are mostly the same. It is initially written to answer a question on CodeProject's QnA. Your C++ project does not have to be MFC to follow the steps described here; it can be console or other types where you can ignore Step 7 to add buttons to MFC dialog because it does not apply to your C++ project type. Note: This example does not cover hosting C# UI element in C++ UI; That is a complex topic.

For simplicity, we are going to use this simple C# class with Add and AddList methods in our C++ project.

using System;

namespace CSharp
    public class CSharpMath
        public int Add(int a, int b)
            return a + b;

        public int AddList(List<int> arr)
            int sum = 0;
            foreach(int n in arr)
                sum += n;

            return sum;

Step 1: Open the MFC project's properties by right-clicking the project in the Solution Explorer and selecting Properties.

Project Properties

Step 2: The Properties Pages dialog shows up. Enable the .NET CLR. The .NET Framework version has to be the same as your C# library.

Enable CLR

Step 3: Add the reference to the C# library in the MFC project by right-clicking on the Reference node and selecting Add Reference...

Add reference by right-clicking on project

Check on the C# project which you want to add reference.

Check the CSharp library reference

Step 4: Next, we'll add a build dependency on the C# project so that whenever MFC/C++ is built, Visual Studio will build the C# project first.

Right-licking on a project dependency

Check the C# project for the build dependency.

Check the CSharp library project as build dependency

Step 5: Open the MFC project's properties by right-clicking the project in the solution explorer and selecting Properties. Click on the Configuration Manager.... Make sure all the platforms are the same. The C# project cannot be AnyCPU configuration: it has to be either x86 or x64, matching what the C++ project setting. If x86 or x64 do not exist, then you have to create them from AnyCPU settings.

How to set configuration manager

Step 6: Close the Configuration Manager. Next, we add the /AI switch to the C++ compiler. /AI switch tells the C++ compiler where to find your C# DLL. You must enter four different paths for Debug x86, Debug x64, Release x86 and Release x64. The paths can be relative. See below.

  • /AI"..\..\MFCwithCSharp\CSharpClass\bin\x86\Debug"
  • /AI"..\..\MFCwithCSharp\CSharpClass\bin\x64\Debug" 
  • /AI"..\..\MFCwithCSharp\CSharpClass\bin\x86\Release" 
  • /AI"..\..\MFCwithCSharp\CSharpClass\bin\x64\Release" 

Image 8

Step 7: The last step is to add two buttons called Add and Add List to the MFC project. Double-click the button in the UI designer and an empty button handler will be created for you to call your C# Add or AddList methods.

Add a button to the dialog

Step 8: In the cpp where you will use your C# class, add the using keyword to import your C# DLL. Amend the DLL name according to yours.

#using "CSharpClass.dll"

In our first button handler, add these code to call the C# class's Add(). Make sure the C# class type ends with a hat(^) and use gcnew to instantiate your C# class (Do not use new keyword because it is reserved for instantiating native C++ objects on the heap). It shows the addition result in a message box.

void CMFCwithCSharpDlg::OnBnClickedBtnAdd()
    CSharp::CSharpMath^ mathClass = gcnew CSharp::CSharpMath();
    int result = mathClass->Add(2, 6);

    char buf[200];
    sprintf_s(buf, "Add result: %d", result);
    MessageBoxA(GetSafeHwnd(), buf, "Add", MB_OK);

You can use .NET Base Class Library (BCL) such as List class. Replace the dots with :: in the namespace. Remember to add another button to the MFC dialog to call AddList() and add the code below to the function.

void CMFCwithCSharpDlg::OnBnClickedBtnAddList()
    CSharp::CSharpMath^ mathClass = gcnew CSharp::CSharpMath();

    System::Collections::Generic::List<int>^ myList = 
        gcnew System::Collections::Generic::List<int>();


    int result = mathClass->AddList(myList);

    char buf[200];
    sprintf_s(buf, "Add List result: %d", result);
    MessageBoxA(GetSafeHwnd(), buf, "Add List", MB_OK);

Build your C++ project and the C# project automatically builds first because of the build dependency set in step 4. Click the Add or Add List button. Make sure it does not crash and the result is correct. If you encounter the error of "C# dll cannot be found" on customer computer, you need to copy the C# dll to the C++ executable folder.

That's all for the example. Hopefully, you can use your C# library in your C++ project. Your next step is to master C++/CLI.


  • 12th April, 2023: Updated the AI path from absolute to relative in the article and source code download. Thanks to tyjiang
  • 8th April, 2023: First release


This article, along with any associated source code and files, is licensed under The MIT License

Written By
Software Developer (Senior)
Singapore Singapore
Shao Voon is from Singapore. His interest lies primarily in computer graphics, software optimization, concurrency, security, and Agile methodologies.

In recent years, he shifted focus to software safety research. His hobby is writing a free C++ DirectX photo slideshow application which can be viewed here.

Comments and Discussions

QuestionWhere to place a user defined structure for the List? Pin
tyjiang12-Apr-23 14:43
tyjiang12-Apr-23 14:43 
AnswerRe: Where to place a user defined structure for the List? Pin
Shao Voon Wong12-Apr-23 15:08
mvaShao Voon Wong12-Apr-23 15:08 
QuestionPath for the dll Pin
tyjiang11-Apr-23 15:17
tyjiang11-Apr-23 15:17 
AnswerRe: Path for the dll Pin
Shao Voon Wong11-Apr-23 20:01
mvaShao Voon Wong11-Apr-23 20:01 
GeneralMy vote of 5 Pin
germanredcat10-Apr-23 2:07
germanredcat10-Apr-23 2:07 
Questionexcellent! Pin
Southmountain8-Apr-23 15:23
Southmountain8-Apr-23 15:23 
AnswerRe: excellent! Pin
Shao Voon Wong8-Apr-23 16:29
mvaShao Voon Wong8-Apr-23 16:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.