callback function from c# to c++
Loading
callback function from c# to c++
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sam HobbsPosted Mar 22, 2024, 5:41 PM
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
Simran VermaPosted Mar 22, 2024, 9:58 AM
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#:
And here's how you would call this C++ function from C#:
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.