How can I pass a C# function pointer into CLI/C++ code?
-
14-07-2021 - |
Question
I want unmanaged C++ code to call a C# function as a callback. I have a CLI/C++ class wrapping around the unmanaged code. An instance of this CLI/C++ class exists within the C#.
The C# code looks like the below text. I have a (delegate) function pointer to the callBack method. I have the CLI instance of CLI_class. I want to give it the function pointer somehow in the addValueChangedCallBack function.
public Setup(){
tempFUNC myFuncObj = new tempFUNC(callBack)
CLI_class c=new CLI_class();
c.addValueChangedCallBack(myFuncObj)
}
public delegate void tempFUNC(float x);
void callBack(float x){
....
}
Then in the CLI code I want to do something like this:
void addValueChangedCallback(void (*ManipCallBack)(float)){
unmanagedCPPCLASS.addValueChangedCallback(ManipCallBack)
}
How can I turn the function pointer into a C++ pointer (*)? Also, I cannot reference the C# project in the C++/CLI project because the C# class already references and uses the C++/CLI project. Will there be a dependency issue?
I have seen references on some sites to 'marshaling data' or using 'interop'. I don't understand how they work or what exactly they do from anything I have seen, are these what I should be using?
La solution
You can have both projects reference each other and use System.InteropServices.Runtime.Marshal.GetFunctionPointerForDelegate to get the function pointer.
But if I were you I'd make the C# class ComVisible and have the C++ code call the C# method directly though a COM interface. That way there's no need for a C++/CLI wrapper. Wrappers are always a pain, as you're experiencing. C++/CLI has its uses, but creating wrappers is not it.