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.
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.