Are callback functions equivelent to events in C#(.NET).
What I understand about callback function is, it is a function that is called by a reference to that Function.
Example Code will be:
void cbfunc()
{
printf("called");
}
int main ()
{
void (*callback)(void);
callback=(void *)cbfunc;
callback();
return 0;
}
Now What I dont understand is How is this use full with respect to notifying from the DLL to client.
Suppose I want to do /perform some method1() when I recieve Data on my DLL method2().
Any comparasion with Events in .NET will be helpfull in a great way.
Callbacks and interface classes are great ways to manage your code boundaries. They help create formal boundaries and/or layers in your code instead of lumping everything together. This becomes necessary when working on large software solutions.
Below is an example of how to use callbacks and interface classes. In the library/dll code the only thing that should be exposed to the main executable is the myddl_interface class and the function getMyDllInterface(). Using an interface class like this completely hides the implementation detail from the main executable. The interface class also allows the main executable to register a function with it that will be executed later (i.e. callback).
// Begin library/dll Public Interface used by an executable
class mydll_interface {
public:
typedef void (*callback_func_t)();
public:
virtual void do_something() = 0;
virtual void registerFunction( callback_func_t ) = 0;
};
static mydll_interface* getMyDllInterface();
// End library/dll Public Interface used by an executable
// Begin library/dll Private implementation
class mydll_implementation : public mydll_interface {
public:
void do_something() {
printf("Hello World\n");
_callback_func();
}
void registerFunction( callback_func_t c) {
_callback_func = c;
}
private:
callback_func_t _callback_func;
};
static mydll_interface* getMyDllInterface() {
return new mydll_implementation();
};
// End library/dll Private implementation
// Begin main executable code
void myMainAppFunc() {
printf("hello World Again\n");
}
int main() {
mydll_interface* iface = getMyDllInterface();
iface->registerFunction(&myMainAppFunc);
iface->do_something();
};
// End main executable code
You pass the pointer to a 3rd-party routine (doesn't have to be a DLL) and it is "called back" when notificastion is required, by the cloned pointer.
It is similar to .net events in that the latter are also a type of a callback.
BTW, DLLs are less popular in C++ than they are in .NET. This is due to impossibility of sharing static variables (and therefore, singletons), the problem also known as lack of dynamic linking (in UNIX systems, this is solved with Shared Objects, which are quite a different concept of dynamically loaded library). Static libraries offer a better code reuse strategy.
Callback functions fulfill a similar purpose to delegates in C#.
For example, the Win32 API provides a timing service, that is accessed by calling SetTimer. SetTimer is exported by a system DLL, but the mechanism is exactly the same as if used in a user dll. In your code you would access the timer by doing something like this:
void
CALLBACK
MyTimerCallback(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
// do something
}
...
TIMERPROC fn = &MyTimerCallback;
int delay = 500;
SetTimer(NULL,0,delay,fn);
Calling SetTimer, and passing in the callback function, allows the operating system to call back into the function each time the timer ticks. Of course, there is no multicast capability here, and, especially in the case of SetTimer, the callback function must be a C function or static class method. There is no class or object instance associated with the function.
A similar pattern could be done in .NET - Im sure .NET has its own Timer paradigm but for a moment we could pretend that it implements a SetTimer function that takes a TimerDelegate.
In user code, in an object you would then define the MyTimerProc as a function with a signature that matches the delegate. And invoke it like this
TimerDelegate d = new TimerDelegate(myObject.MyTimerProc);
SetTimer(0,0,delay,d);
Or, if "timers" was an event that matched the TimerDelegate, then the equivalent C# code would look something like:
timers += new TimerDelegate(myObject.MyTimerProc);
Note: My C# is very rusty so don't take those code samples as any kind of example of either best practices, or even working code :P
When defining your own callback functions it is good practice to always define callback functions to take a void* "context" parameter, as that allows C++ programmers to store their "this" pointer and retrieve it.
// the first parameter to the callback fn is a void* user supplied context parameter
typedef void (CALLBACK* MyCallbackFn)(void* context, int etc);
// and, the dll export function always takes a function pointer, context parameter pair.
DLL_EXPORT void SomeExportedFn(MyCallbackFn, void* context);
A notable example is qSort(), it needs a callback function to compare 2 items.
Callback function can leave some behavior decided at runtime.
If some behavior should be decided by client side dynamically at runtime, then I will ask clients to supply callback functions.
Related
Currently, I am working on a project in C# which use C++ libraries. To use the C++ libraries they are wrapped in CLR. Communication between the C++ and C# are in both ways.
I have the following problem. At a point the C++ calls some functions in CLR which will raise events with objects that have C++ raw pointers.
For example:
C++ object
class CObject {
private:
char* ptr;
}
CLR object
ref class CLRObject {
public: CLRObject(CObject* p) : m_native(p) {}
private: CObject* m_native;
}
C# object
class CSHObject : CLRObject {
}
Now because CSHObject is send as an argument to the event to multiple handlers they will all get a reference to the same object. So when one of the event handlers will modify the object which is pass by the event, the other listeners of the event will get the modified object.
For example:
C++ creates the object:
void updateListeners() {
updateListener(new CObject());
}
CLR overwrites the updateListener:
void updateListener(CObject* obj) {
m_wrapper->updateListener(gcnew CLRObject(obj))
}
C# will raise the event:
public event EventHandler<MyEventArgs> MyEvent;
void updateListener(CLRObject obj) {
MyEvent?.Invoke(this, new MyEventArgs(new CSHObject(obj)));
}
Now my question, how we should handle these events? from the point of MVVM view. Because the CLRObject is the Model in this case, but the same model is shared between multiple view models. Which I think is not the correct way of the MVVM.
So:
should all the event listeners create their own Models and copy the required information from the CLRObject?
each event listener create a deep copy of the object?
the current implementation is the correct way and I should not change.
Obs:
I don't have good knowledge in C#, CLR.
All the example code is made up, because the real code is too long and contains a lot of other things.
I spent about 3 days reading about this topic...
I am totally lost now thanks to the many tutorials and answered questions about how to create a native DLL. If you have some time to spare please care to explain a little about the topic and help me - if you don't have time then just go to the simple form of my question down there...
Here is what I know about the topic so far:
1) I need to use a macro defined as __declspec(ddlexport) and __declspec(ddlimport) before class name to export all the class methods and variables
2) I need to use extern "C" somewhere but I am not sure exactly where
3) There are many ways to do this (pass class as parameter to methods that accept it c approch/ export class / use interface)
Here is why and how I am lost:
1) Most of tutorials are for exporting methods, which I suspect is very easy compared to classes (in C# you use [Dllimport, name of DLL] then you invoke each method)
2) Do i need to use extern "C" with classes or not?
3) If I used a factory method with an interface do i need distribute the .h file containing the interface?
Here is what i want to do:
1) create a C++ DLL with a class in it and to export that class to be used in .NET or C++ (I want to protect my code, since I saw how easily you can reverse managed code using the stored IL.)
2) I want to have 2 DLLs, one C++ native DLL, and the other one will be the wrapper DLL, so that if someone wants to use my class in C++ he can use the native DLL directly and if he wants to use it in C#/VB.net he can use the C++/CLI wrapper DLL...
3) no libs, no header files, no def files,...etc..... only pure DLLs (2 files will be released)
Simple form
Let's say I want to instantiate an object in C# from this C++ class
Class Human
{
private:
int Pee_Meter;
public:
Void Do_Pee()
{
//stuff here
};
};
What do I need to do, basic stuff only? With the least possible number of files and maximum code protection, no releasing of header files or anything, only using DLLs and probably a txt file that mention methods names and stuff to use in DLL.
In other words, are these steps correct?
1) In VS2012 create new Win32 project, then select DLL as type of project
2) define macro __declspec(ddlexport) / __declspec(ddlimport) and use it before class name (should I use extern "C" with classes? Probably not...)
3) Compile DLL
4) Create a CLR project in VS2012 to use C++/CLI
5) Link the native DLL (I don't know how?? PInvoke entire class???????)
6) Define wrapper class (which I am still learning, but I think you create a method in CLI for every method in native class)
7) Compile the CLI DLL
Should I say that I have Deitel and Ditel C // Deitel and Ditel C++ // C++ programming by D. S. Malik and non of these three books mention anything about making DLLs which I think is kind of stupid.
Finally, thank you for every second you wasted in helping me, I really appreciate every help you provide even if you directed me toward a tutorial that I have read before... I might have missed something in it :)
Having done this a bunch of times, the easiest way to do this is to write a C++/CLI wrapper to your existing classes. The reason being that P/Invoke works best on calls that are strictly C functions and not methods in a C++ class. In your example, how would you call operator new for the class that you specify?
If you can write this as a C++/CLI dll, then what you get is something that looks like this:
public ref class CliHuman {
public:
CliHuman() : _human(new Human()) { }
~CliHuman() { delete _human; }
protected:
!CliHuman() { delete _human; }
public:
void DoPee() { _human->Do_Pee(); }
private:
Human *_human;
};
Now, you might not have the freedom to do this. In this case, your best bet is to think about what it would take to expose a C API of your C++ object. For example:
extern "C" {
void *HumanCreate() { return (void *)new Human(); }
void HumanDestroy(void *p) { Human *h = (Human *)h; delete h; }
void HumanDoPee(void *p) { Human *h = (Human *)h; h->Pee(); }
};
You can P/Invoke into these wrappers very easily.
From an engineering standpoint, you would never want to do this ever since calling .NET code could pass in any arbitrary IntPtr. In my code, I like to do something like this:
#define kHumanMagic 0xbeefbeef;
typedef struct {
int magic;
Human *human;
} t_human;
static void *AllocateHuman()
{
t_human *h = (t_human *)malloc(sizeof(t_human));
if (!h) return 0;
h->magic = kHumanMagic;
h->human = new Human();
return h;
}
static void FreeHuman(void *p) /* p has been verified */
{
if (!p) return;
t_human *h = (t_human)p;
delete h->human;
h->human = 0;
h->magic = 0;
free(h);
}
static Human *HumanFromPtr(void *p)
{
if (!p) return 0;
t_human *h = (t_human *)p;
if (h->magic != kHumanMagic) return 0;
return h->human;
}
void *HumanCreate() { return AllocateHuman(); }
void HumanDestroy(void *p)
{
Human *h = HumanFromPtr(p);
if (h) {
FreeHuman(p);
}
else { /* error handling */ }
}
void HumanPee(void *p)
{
Human *h = HumanFromPtr(p);
if (h) h->Do_Pee();
else { /* error handling */ }
}
What you can see that I've done is create a light wrapper on top of the class that lets me verify that what comes in is more likely to be a correct pointer to what we want. The safety is likely not for your clients but for you - if you have to wrap a ton of classes, this will be more likely to catch errors in your code where you use one wrapper in place of another.
In my code base, we have found it especially useful to have a structure where we build a static library with the low-level code and the C-ish API on top of it then link that into a C++/CLI project that calls it (although I suppose to could P/Invoke into it from C# as well) instead of having the C++/CLI directly wrap the C++. The reason is that (to our surprise), all the low-level code which was using STL, was having the STL implementations done in CLI rather than in x86 or x64. This meant that supposedly low-level code that was iterating over STL collections would do something like 4n CLI transitions. By isolating the code, we worked around that quite well.
I think you'd be better off making a plain C interface to your C++ code. C++ linking is really only good for other C++ programs, due to name mangling. C functions, however, can be used in many languages without any problem - python, C#, haskell, etc.
Let's suppose, however, you want to have some C++ classes accessible from your C interface. The way I like to do this is:
in my C++ dll have a global object registry. basically a map from int to object.
whenever I create an object, it gets a new registry ID.
whenever I call a function that uses the object, I pass in the ID.
so something like this:
int CreateNiftyInstance()
{
int i = global_store.get_id();
Nifty *n = new Nifty();
global_store.save_obj(i, n);
return i;
}
void DoSomethingNifty(int id, const char *aCData)
{
// lame dynamic cast. Making it type safe is possible with dedicated stores for
// each type of object.
Nifty *n = dynamic_cast<Nifty*>(global_store.get_obj(i));
if n
{
n->DoSomething(aCData);
}
}
ah i think I found what I was looking for after reading this [http://www.codeproject.com/Articles/9405/Using-classes-exported-from-a-DLL-using-LoadLibrar]
correct me if wrong
first I need to either export the native class or mark a factory method as extern "C"
then in the CLR project I use the factory method or use Loadlibrary + malloc commands to get an instance of the class if I did not go with the factory method approach
create the wrapper class as plinth had told me to do (many thanx to him). and use the instance from the previous step to call methods in my class
include both dlls in the release and instructe developers to reference the CLR dll only.
if that is the way then iam very greatfull for all of you guys
going to start working on it soon...
Yours...
I'm trying to PInvoke into this C++ library function:
int Initialize(Callback* callback);
struct Callback
{
//.......
void virtual StateChanged(int state) = 0;
};
I have tried this naive C# code, but it doesn't work.
[DllImport("CPlusPlusLibrary.dll", SetLastError = true, EntryPoint = "?Initialize#CPlusPlusLibrary##YAHPAUCallback#1##Z")]
public static extern int Initialize(Callback callback);
[StructLayout(LayoutKind.Sequential)]
public class Callback
{
//....
public delegate void IntDelegate(int state);
public IntDelegate StateChanged(int state);
}
var callback = new Callback();
var result = Initialize(callback);
It is impossible to do it that way as far as I know. Methods are not "in there" as fields would be, beside this, creating a struct with virtual method will create a vtable pointer in your objects, that you are not taking into account in c# mirrored class.
What you can do is to PInvoke to method that takes a functionPointer (in C++) and pass a delegate (C#) there. You can then use this function pointer to call it from native code and your delegate will launch.
You could then change your stateChange method definition to take a Callback* as a first parameter, so when you call it from native code you can pass an object pointer which is responsible of that change and marshal it back to Callback in c#.
//Edit without having source of native dll, building a bridge between c# and c++ is what comes to my mind. This can be done with c++/cli or c++, sticking to native my idea would be something like this:
//c++ <--> new c++ dll <--> c#
struct CallbackBridge : public Callback
{
void (*_stateChanged)(int);
virtual void stateChanged(int state)
{
if (_stateChanged)
_stateChanged(this, state);
}
};
void* CreateCallback() { return new CallbackBridge(); }
void DeleteCallback(void* callback); { delete callback; }
void setStateChanged(void* callback, void (*ptr)(void*, int))
{
CallbackBridge* bridge = (CallbackBridge*)callback;
bridge->stateChanged = ptr;
}
///... other helper methods
The idea here is to treat your object as a black box (hence void* everywhere - it can be any pointer, but from c# you will just see this a a SafeHandle / IntPtr and write helper methods that you can PInvoke to to create / delete and modify objects. You can mock those virtual calls by giving your object a delegate through such method.
From c# usage could look like this: (IntPtr for simplicity, SafeHandle could be used):
IntPtr callback = CreateCallback();
SetStateChanged(callback, myCallback);
//somewhere later:
DeleteCallback(callback);
void MyCallback(IntrPtr callback, int state)
{
int someData = SomeOtherHelperMethod(callback);
ConsoleWrite("SomeData of callback is {0} and it has changed it's state to {1}", someData, state);
}
I know, it's a bit clumsy for bigger objects, but without c++/cli wrapper I have never found any better way to be able to handle all those tricky cases like virtual calls etc.
Your C# class is no substitute for the C++ struct, it has an entirely different internal organization. The C++ struct has a v-table because of the virtual method. It is not a POD type anymore. It has a hidden field that contains a pointer to the v-table. And a compiler-generated constructor and destructor. The v-table is an array of pointers to the virtual methods. A C# class has something similar, called "method table", but it organized completely differently. It will have the System.Object methods for example and contains pointers to all methods, not just the virtual ones. The class object layout is completely different as well. The struct keyword in the C++ language in this context is just a substitute for the class keyword with all members public by default.
A wrapper class written in the C++/CLI language is required. There's a bit of a learning curve to the language but it is not steep if you've got experience with .NET and C++. Boilerplate code for such a wrapper is in this answer. You can call back from native code into managed code through a function pointer returned by Marshal::GetFunctionPointerForDelegate().
I have heard that you don't have the source code of C++ library. Then you might have a look at this.
But exporting classes from unmanaged dll to managed one without source sounds dangerous to me.
I would have to call C++ code from .Net code via interop.
I just wonder whether is there anyway to interop with another function in a different class? For example, in C++, I have the following utility class:
class ConvertUtility
{
public:
static void Convert(PointList &ptList, const list<pts> &pts);
};
I wish to call it directly from .Net via interop, any idea how to do this?
Note: here's a related question asking about how to use namespace to distinguish between different method. But this time, I want nothing to do with namespace, only a class with static function.
Edit: Given that there are already too many functions in the C wrapper ( e.g, static extern "C" function that are callable from .Net, without class or namespace), I won't want to introduce an extra layer of wrapping, if I can help it.
In the related question you linked to, Ben Voigt says in a comment to the suggestion to write a C++/CLI wrapper:
This IS the correct answer. P/Invoke should only be used to call
functions with a "C" interface, which means extern "C" to prevent name
mangling, and also restrictions on parameter and return types.
Since the method is static, I see two options:
Write a simple C wrapper function that can be called with P/Invoke.
Write a C++/CLI wrapper that can be called directly from C#.
First I should tell you that ive little knowledge of Objective C or C#.So when one of my collegues asked me whether there is anything like delegates in Objective C,I wondered if such a concept existed in Objective-C.I guess the delegates we use in iphone programing are not the same.C# delegates are function pointers right? Such a facility would be nice to have while working with multiple views.Where can i find info??
Delegates in Objective-C are merely a concept, not some kind of implementation artifact (like in C#). A delegate in Objective-C (better: Cocoa) is basically an object, which is notified by whoever uses it as its "delegate" of certain events occuring. Delegates may also be asked to perform certain tasks on behalf of the host object. The interface a delegate is required to implement is often formalized by a protocol.
#protocol ActionDelegate
- (void) actionDidStart: (id) aSender;
- (void) actionDidEnd: (id) aSender;
#end
#interface Action: NSObject {
id<ActionDelegate> delegate;
}
#property (nonatomic,assign) id<ActionDelegate> delegate;
#end
Delegates in C#, on the other hand, are an implementation artifact. There is a dedicated delegate keyword to declare delegate types and to create actual delegate instances.
class Action {
delegate void ActionDidStartDelegate(Action sender);
delegate void ActionDidEndDelegate(Action sender);
...
}
(my C# is a bit rusty, so the syntax may be off here, sorry; and in real life, one would probably use events in situations like the above rather than raw delegates). Basically, a C# delegate is akin to a Python method object.
You might be able to use the new code block feature of Objective-C to emulate delegates. Not having used this feature (yet), I cannot comment on this. Another way to get something like that would be to use plain function pointers.
typedef void (*callback_function)();
- (void) doSomethingWithCallback: (callback_function) func {
...
func();
}
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
- (void) doSomethingWhenDonePerform: (SEL)aSelector onObject: (id) aReceiver {
...
[aReceiver perform: aSelector];
}
C# delegates are something like NSInvocations in Objective-C:
each knows the object that will be the target of the call
each knows the method that will be called
however, an NSInvocation goes further:
it knows the arguments to pass to the method
it can store the return value
You probably wouldn't use NSInvocation to implement a pattern like C# delegates (which are a form of Proxy pattern). Personally I'd choose to use an object that forwards messages it receives to the target object, using the standard message-forwarding features of the runtime.