C Library Callback in C++ without pointer to "this" - c++

I have a C library here which I want to wrap in a C++ class. The library works asynchronous and needs to set an error handler. I know how to wrap an error handler in a static class function for a C library, but I am used to having something like a void *user_data pointer, where I can put this in to call a member function from the static thunk.
Is there a way to register the callback for a member function directly, as this library does not feature a pointer to some userdata?

You can wrap it in your own static function which is aware of some global (or static local) object on which it is to operate. You can even make this function a static method if want, but you can't call a method on an object without supplying an object on which it is to be called.
Edit : having thought about it for a while, maybe there is a way. You can essentially emulate thread-local storage by having a global collection of collections of states indexed by thread id. Within each thread-bound collection of states you can keep a stack/queue (depending on how the data are processed) of calling objects. The callback can look up the stored queue (because the callback knows the thread id in which it is running). This would allow you to force a single-threaded framework to operate on multiple streams of data.

Related

Callback concept and normal calling

I'm so confused
we know that all functions defined as global so we can call and use any function inside any block without passing it as argument
why we use Function callback concept while we can use a function inside any function without passing it
so why we use callback concept ?
For the same reason you use variables instead of constants.
Passing a callback to a function allow that function to call a different callback depending on how it was called.
Calling a function by name inside a function will always call that one function.
The call back concept means to provide some other function with a function to call when it needs something to be done, e.g. when an event happens. It also often means we can change the function to be called in run-time.
In this way, the knowledge of when to call what is not needed by the calling function. For example, a 3rd party library defines callbacks for the user's program to "plug-in" functionality into the library, or to be called when an event occurrs, a state is reached or an error occurrs and the library needs to know what to do about the error.
This is just a simple answer. Google around to find more information and see https://en.wikipedia.org/wiki/Callback_(computer_programming)

luabind : Accessing an invalidated c++ object from lua results in access violation

Is it possible that luabind checks, if a member function call to an exported class (object) is for a valid object?
lets assume that i have a Class called Actor exposed using luabind to lua. Im calling a lua function from C++ with an actor object as parameter. Now before the function finishes, a script write would put the actor object in a global lua reference to be accessed later.
Later on, the actor object is deleted from the C++ site, another function is called which tries to access the invalidated actor object (any method from it) - and obviously since it has been deleted, it results in a crash (access violation)
sample:
local myObjRef = nil
function doSomethingWithActor(actor)
-- save, still valid object
actor:Say("hello")
myObjRef = actor
end
function calledAfterActorWasDeleted()
--- will crash if the c++ object has been deleted meanwhile, works fine if it still exists
myObjRef:Say("Crash...")
end
A NIL check doesnt help here, is this something that can be checked on luabinds site? The functions are executed using lua_pcall(....) and the stacktrace shows the error at luabinds call.hpp results = maybe_yield(L, lua_gettop(L) - arguments, (Policies*)0);
If not, is there another solution how to make sure somebody who writes a script cannot create these issues?
Now before the function finishes, a script write would put the actor object in a global lua reference to be accessed later.
That right there is where your problem is coming from. If you want Lua code to own the object (that is, preserve the existence of this object), then you need to use Luabind mechanics to tell Luabind that you want to do that. Otherwise, if you pass a pointer to some Lua function, Luabind will assume that the function will not be trying to gain ownership of it.
If you want ownership to be shared between Lua and Luabind, then you should wrap your objects in a boost::shared_ptr, and use Luabind's smart pointer mechanisms to do this.
You could also simply segregate your scripts better. If you have some script that operates on a particular actor, then that script and any functions it contains should be destroyed (ie: lose all references to it) along with the object. This requires proper coding discipline on the C++ side. It will also require that you use Lua environments to properly encapsulate each instance of a script, so that they can't sneak things out via globals. Lastly, you will need to have C++ maintain total control over when scripts are called and when they aren't.
Otherwise, ownership is something your scripters are simply going to have to know about and be careful of. They can't treat C++ parameters like any old Lua value.
If exercising disciplined programming practice is not possible or practical for you, then you will simply have to not pass Lua the actual C++ object. Instead, you need to pass Lua some proxy object, which is a reference to the original. boost::weak_ptr is a good example of such an object (though you wouldn't pass it exactly to Lua). The proxy would forward calls to the actual object. If the object has been deleted, the proxy would detect this and fail or do nothing or whatever.
I solved my issue the following way:
When im about to delete an object, i iterate through all lua functions from C++ (i have them in a list, they are bound to specific actor objects each). Then i inspect each upvalue (global/local vars accessable to a function) - then i compare the userdata pointer with my object im about to delete - if they match (and their classes) and NIL the upvalue. Optionally, i could just remove that offending function because it would not work well anymore anyway.
So the next the time the function is called, im just getting a soft lua error "trying to access xxx a nil value..." - no more access violations.
I know people would say "dont use lua_getupvalue/lua_setupvalue - they are only for debugging!" - but there is actually no documented or spoken side effect - and in my case its perfectly safe and works well - also there isnt the issue with left over proxy objects i could not delete.

Member pointers or reference arguments?

I have the following problem.
I got a class PluginLoader which oversees loading of plugins. It divides sub-stages of work to other classes like Plugin. Plugin calls functions of PluginLoader in its processing. Let's call that function AddData. Here, PluginLoader has to check if the data it receives is duplicate. For that, it uses a ConflictResolver class. Now, my problem is how to make an object of ConflictResolver available to PluginLoader. There are 3 ways I see out of this.
Use a ConflictResolverFactory class and create an object of ConflictResolver for PluginLoader.
Pass a constructed ConflictResolver* to the PluginLoader via its constructor or a member function SetConflictResolver and store it in a member variable and use it later. Both ways have drawbacks. If I pass it in the constructor, I will have to throw if the pointer is NULL. And I can't use exceptions as it is the custom here. If I pass it via SetConflictResolver, there is no way that I can guarantee that that function will be actually called by the user. Or I will have to check whether the member ConflictResolver* is NULL everywhere I use it.
Pass a ConflictResolver & to PluginLoaders Load method where all the work will be done. In turn, Plugins Load method has to accept a ConflictResolver & as well (though it has no use for it) and pass that back to AddData where PluginLoader will be able to use it.
Third method is safer compared to second. However, I have to pass around a reference even when it is not used.
If the first method cannot be used, what is the best way to do this?
Apologies for the wall :wq!
You could pass a ConflictResolver& to the PluginLoader constructor. You can now guarantee that the object is not null.

C API function callbacks into C++ member function code

So, I'm using the FMOD api and it really is a C api.
Not that that's bad or anything. Its just it doesn't interface well with C++ code.
For example, using
FMOD_Channel_SetCallback( channel, callbackFunc ) ;
It wants a C-style function for callbackFunc, but I want to pass it a member function of a class.
I ended up using the Win32 trick for this, making the member function static. It then works as a callback into FMOD.
Now I have to hack apart my code to make some of the members static, just to account for FMOD's C-ness.
I wonder if its possible in FMOD or if there's a work around to link up the callback to a specific C++ object's instance member function (not a static function). It would be much smoother.
You cannot directly pass a member function. A member function has the implicit parameter this and C functions don't.
You'll need to create a trampoline (not sure the signature of the callback, so just doing something random here).
extern "C" int fmod_callback( ... args ...)
{
return object->member();
}
One issue is where does that object pointer come from. Hopefully, fmod gives you a generic context value that will be provided to you when your callback is made (you can then pass in the object pointer).
If not, you'll just need to make it a global to access it.
I guess it supposed to work like this:
You can assign some user data to channel by calling FMOD_Channel_SetUserData. This user data should be a pointer to your C++ object that handles events.
Then you should write C-style callback that extracts that object by calling FMOD_Channel_GetUserData and then calls your C++ instance method on that object.
There is a non-portable, and pretty hackish solution that has the advantage of at least being thread-safe, which the "trampoline" methods are not.
You can generate the actual function machine code on the fly. The basic idea is that you have a template for your call-back function that takes an object pointer and a member-function pointer and gives you a block of heap memory that you can pass to the library as a C call-back function, that will, when called, turn around and call the member function on that object.
It's messy, and you'll have to provide an implementation for any new platform (any time the calling convention changes), but it works, is thread-safe. (Of course you'll also have to watch out for DEP). The other thread-safe solution is to resort to thread-local storage (assuming that you know the call-back will happen on the same thread as the call you made).
See http://www.codeproject.com/KB/cpp/GenericThunks.aspx for an example of how you could go about generating thunks.
Using only a function pointer (and no additional separate object pointer) for a C callback is a broken design, in my humble opinion.
If the function were, instead, FMOD_Channel_SetCallback(channel, callbackFunc, callbackObj), then your static method just takes an instance of the object, then calls callbackObj->func() (which obviously can be non-static).
you need to use a trampoline and store the pointer to the object you want to get the member function called on in a global or static variable, i.e.
Object *x;
void callback_trampoline() { x->foobar(); }
...
FMOD_Channel_SetCallback(CHANNEL, callback_trampoline);

What is the best technique to create a thread in C++ while passing the class and an index?

I am creating a data-parallel program using pthreads and C++. From pthread function from a class, I found out how to supply pthread_create with a function pointer to a static C++ function(and supply it a this argument).
However, I also need to supply the thread with an index, so it knows what data it's working on. I could malloc a struct for each thread(with both the pointer to the C++ class and an index), but this seems like it would add some bookkeeping code, and could lead to leaks if the struct isn't freed. Is there a better way to do this?
You can use Boost.Thread. It provides a type-safe way for you to pass more than one argument into your callable.
Yes, it has similar kinds of bookkeeping as your question stated, but it uses C++ mechanisms to ensure that it doesn't leak.
Is there a better way to do this?
Not really. Since thread functions can only take a single void * argument, any and all data that you want to pass to the thread function has to be part of a struct or class that contains the data you need. The usual design pattern is to have a ThreadParameters class or struct that contains everything that you need, and which you can add to if you need to have more parameters.
The most straightforward way to handle freeing is to have the person that creates the thread allocate the ThreadParameters, and have the thread itself free the ThreadParameters just before it exits.
Unless you are passing the same C++ object as the this pointer to multiple concurrent threads, you should simply add the index to the object.
I would recommend having one object per thread, to make debugging easier if nothing else. Make your current this class a resource shared by reference between thread objects.
If that means adding new objects on the heap, simply delete them immediately after calling pthread_join. Not much room for error, really.
If there is an object (class instance) associated with each thread. (I inferred this from your reference to this.) You could just make the index a member of the class. This could be configured in the constructor or using alternatively using a setter.
class C {
Index index_;
public:
C(Index &index) : index_(idx) {}
void Run() { ... }
}
Index workSet;
C worker(workSet);
worker.Run();