Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C#
Tip/Trick

Interoperability between C++ and C#

Rate me:
Please Sign up or sign in to vote.
4.86/5 (8 votes)
13 Dec 2023CPOL1 min read 10.1K   14   3
Demo of how C++ and C# interoperate
In this article, I demonstrate how to call a C++ function, set a callback function in C#, and output showcasing the successful callback from C++ to C#.

Let's see a simple code example here:

C#
internal class CallbackfromCpp
{
    // Delegate definition for the callback function

    public delegate void CallbackDelegate(string result);
    [DllImport("CallBackC.dll", CallingConvention = CallingConvention.Cdecl,
                CharSet = CharSet.Ansi)]
    public static extern int Add
           (int a, int b, string input, CallbackDelegate callback);

    // Callback function in C#
    public static void MyCallback(string result)
    {
        Console.WriteLine("Callback invoked from C++ with result: " + result);
    }
    public void RunAdd()
    {
        int res = Add(9, 8, "res", MyCallback);
        Console.WriteLine("the result of Add function: " + res);
    }
}

In class CallbackfromCpp, we define a delegate, declare a function whose name is same as a function in CallBackC.dll. Then we set a function MyCallback for the delegate with same signature list. It will print the parameter passed by its caller. Finally, let's see the entry method RunAdd. It calls the Add function with parameters (9, 8, "res", MyCallback) and stores the return value in res.

Run CallbackfromCpp.RunAdd() and you'll see the output below:

Shell
Callback invoked from C++ with result: res
the result of Add function: 17

It's widely known that if you want to call C++ function in C#, you need a C++ DLL with the target function you want to use and then use the DllImport attribute in a function declaration in your C# code. In this example, the function is Add. This is how we get the second line in control panel. But for the first line, it's obviously from MyCallback.

How is the MyCallback function being called in C++? The third parameter in function, Add, is CallbackFunction type, we can see from the typedef above the function signature. It's actually __stdcall. So it's a pointer passed by the caller and Add function will pass the parameter c to the pointer. Then C# code will execute the delegate!

C++
// CallBackC.cpp
#include "CallBackC.h"

int Add(int a, int b,char *c, CallbackFunction callback) {
    int result = a + b;

    // Invoke the callback function
    if (callback != nullptr) {
        callback(c);
    }

    return result;
}

// CallBackC.h
#pragma once

// Define a callback function signature
typedef void(__stdcall* CallbackFunction)(char* result);

// Export the Add function directly
extern "C" __declspec(dllimport) int Add(int a, int b,char *c, CallbackFunction callback);

History

  • 14th December, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA31-Dec-23 19:55
professionalȘtefan-Mihai MOGA31-Dec-23 19:55 
GeneralMy vote of 5 Pin
Jan Heckman14-Dec-23 0:30
professionalJan Heckman14-Dec-23 0:30 
QuestionWhat does "dllimport" and "dllexport" mean? Pin
FenrisH13-Dec-23 15:24
FenrisH13-Dec-23 15:24 

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.