Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Simran VermaRank #831 · 2.7K reputationPosted Mar 22, 2024, 5:58 AM EDT
To call a C++ function from C#, you can use Platform Invocation Services (P/Invoke). Here's a basic example demonstrating how to achieve this:
Let's say you have a C++ function that you want to call from C#:
// C++ code #include extern "C" { typedef void(*CallbackFunc)(int); __declspec(dllexport) void RegisterCallback(CallbackFunc callback) { // Invoke the callback function with some value callback(42); } }And here's how you would call this C++ function from C#:
// C# code using System; using System.Runtime.InteropServices; class Program { // Define the delegate to match the callback function signature delegate void CallbackDelegate(int value); // Import the C++ function [DllImport("YourCppLibrary.dll")] private static extern void RegisterCallback(CallbackDelegate callback); // Define the callback function static void MyCallback(int value) { Console.WriteLine($"Callback received value: {value}"); } static void Main() { // Call the C++ function and pass the callback function RegisterCallback(MyCallback); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }In this example:
RegisterCallbackthat takes a function pointer as an argument.CallbackDelegateto match the signature of the callback function expected by the C++ function.RegisterCallbackfunction from the C++ DLL using theDllImportattribute.MyCallbackin C#, and pass it as an argument when callingRegisterCallback.RegisterCallbackis invoked, it calls back the provided function pointer, which is the C# functionMyCallback, passing the value42.MyCallbackfunction in C# is executed, printing the received value.Remember to replace
"YourCppLibrary.dll"with the actual name of your compiled C++ DLL. Additionally, ensure that the C++ function is marked for export using__declspec(dllexport)or appropriate methods based on your compiler.Sam HobbsRank #107 · 20.5K reputationPosted Mar 22, 2024, 1:41 PM EDT
Can you provide details of the requirements? Since you say callback I assume that a C++ program is calling a C# program that you want to call C++ from. How does the C++ program call the C# program? Is the C++ program managed C++?
I have written the following articles that might be relevant but I need more information to be able to be specific.
Native Windows Dynamic Link Libraries (DLLs)
https://www.c-sharpcorner.com/UploadFile/SamTomato/native-windows-dynamic-link-libraries-dlls
Managed C++ Wrapper For Unmanaged Code
https://www.c-sharpcorner.com/UploadFile/SamTomato/managed-cpp-wrapper-for-unmanaged-code