Passing C++ captureless lambda as function pointer to C API
文章推薦指數: 80 %
A lambda expression with an empty capture clause is convertible to a function pointer. It can replace a stand-alone or static member function as ...
nextptr
SignIn
SignUp
PassingC++capturelesslambdaasfunctionpointertoCAPI
Alambdaexpressionwithanemptycaptureclauseisconvertibletoafunctionpointer.Itcanreplaceastand-aloneorstaticmemberfunctionasacallbackfunctionpointerargumenttoCAPI.
Tutorial|Sep6,2019|jmiller
c++
lambda
pthreads
function-pointer
c++11
Quiteoften,C++applicationsdependonthird-partyoroperatingsystemlibrariesthatareentirelywritteninCorexposeC-onlyinterface.SomeexamplesoftheseC-APIsaredatabasedrivers,messagingserviceAPIs,andnativethreadinginterfaces.Usually,theseC-APIstakefunctionpointerparametersforcallbackarguments.Let'staketheexampleofpthread_createfromthePOSIXpthreadlibrary.
intpthread_create(pthread_t*thread,constpthread_attr_t*attr,
void*(*start_routine)(void*),void*arg);
Thepthread_createfunctioncreatesanewthreadthatstartsexecutionbyinvokingtheparameter,start_routine.Thelastparameter,arg,ispassedastheargumenttostart_routine.
Suppose,wearecreatingaWorkerclassthatperiodicallydoessomeworkinabackgroundthread.TheWorker'sstartmethodcreatesanewthreadthroughpthread_create.ThenewbackgroundthreadalwaysexecutesinaloopintheWorker'srunmethoduntiltheloopisterminated.Thestopmethodsetsabooleanflagtoendtherunloopandjoinsthethread.BelowisthecodeoftheWorkerclass:
//requirespthread.handunistd.h
classWorker{
public:
//Implementedlater
intstart();
voidstop(){
stopped_=true;
//waitforthethreadtoexitbyjoining
pthread_join(threadId_,nullptr);
}
private:
voidrun(){
while(!stopped_){
std::cout<void*{//capture-lesslambda
static_cast
延伸文章資訊
- 112.7 — Introduction to lambdas (anonymous functions) - Learn C++
- 2c++裡的bind和lambda,為什麼沒辦法變成c-style function ...
在c裡面,function pointer是一個儲存function位置的指標,可以拿來pass一個function讓別人呼叫,通常用來實作callback function。
- 3In C++, what is the reasoning behind not allowing function ...
I'm not a C++ programmer, but wouldn't that cause loss of information? I mean, the lambda also ha...
- 4Lambda Expressions vs Function Pointers - GeeksforGeeks
A Lambda expression is also called an anonymous function. It is an expression contained within th...
- 5Passing capturing lambda as function pointer - Stack Overflow
A lambda can only be converted to a function pointer if it does not capture, ... I am using this ...