Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call C++ Function from C#? (VS 22)

I’m attempting to find out whether it’s possible to call a function defined in a C++ file from a C# file. I’m using the WinForm template in Visual Studio 2022 as a simple example.

I have a single test function defined in my C++ file:

#include <iostream>

void test()
{
    std::cout << "test\n";
}

And that file is located in the root folder of my C# WinForm project.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was aiming to do something like this in my C# WinForm file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Fun_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //test();   <- call C++ function from here
        }
    }
}

Is something like this even possible to do in C# with VS 2022?

Thanks for reading my post, any guidance is appreciated.

>Solution :

You can call a C-style function from C# using P/Invoke. But the function need to be exported, be compiled to a dll, and have a compatible signature. There all sorts of rules on how things like strings, arrays and delegates are converted to their C equivalents.

So you cannot just plop down a C++ function in your C# project and hope anything will work. You still need a separate project to compile the function to a dll.

Then there is C++/CLI that is a kind of hybrid between .Net and c++. But you still need a separate project for it to work.

But the main reason to use native interop is when some library is not available in .Net. You would rarely split the codebase by purpose. There might be some cases where it could be motivated by performance, but then you should first try all the tricks possible to optimize the C# code first.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading