|
Boost Users : |
Subject: Re: [Boost-users] boost::bind for C function
From: Philipp Kraus (philipp.kraus_at_[hidden])
Date: 2012-12-21 06:29:49
On 2012-12-21 10:21:09 +0100, Kevin Martin said:
> On 20 Dec 2012, at 23:30, Philipp Kraus wrote:
>
>> So I would like to use boost::bind / boost::function to create the binding
>> to a class method:
>>
>> boost::function<CFunction>( boost::bind(&MyClass::myMethod, this) )
>
>
> As Lars Viklund said, boost::bind returns an object, whereas a
> c-function is just a pointer - it is not possible to convert an object
> into a pointer.
>
> Assuming this is Lua (based on your posts of lua-l and the typedef). I
> think you have two choices. If this is about another API then ignore
> the rest of the message!
>
> 1) If you really need to use boost::bind then you need to have some way
> to box the object in lua. This is relatively complicated, and
> completely unnecessary to simply call a class method. However, I can
> provide an example if necessary.
>
> 2) Create a closure with the object's address stored as a lightuserdata.
>
> int callobjectmethod(lua_State *l) {
> Object *x = (Object *)lua_tolightuserdata(l, lua_upvalueindex(1));
> return x->method(l); //Make sure this doesn't throw, or enclose in try/catch
> }
>
> Instead of using lua_pushcfunction, you should use lua_pushcclosure as follows
>
> Object o;
> lua_pushlightuserdata(l, &o);
> lua_pushcclosure(l, callobjectmethod, 1);
>
> You must remember you you are responsible for the lifetime of the
> object and must keep it in scope while the closure still exists.
>
> There are many ways to achieve what you're trying to do, and the most
> appropriate depends on many things. Lua has a beautifully simplistic
> API, that doesn't take long to learn with the right materials. The PiL3
> book comes out soon, I suggest you spend some time reading it, as it
> will help you enormously with these kind of problems.
Thanks, I use exactly this structure and I will add a seperate
definition for C++11. It is the best way and in my case the closure
exists during the lifetime of my object
in the ctor the this pointer will be used and in the dtor the closure
will be removed.
Thanks
Phil
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net