Bagaimana untuk Melepasi Boost::function kepada Kaedah Menjangkakan Penunjuk Fungsi?

Mary-Kate Olsen
Lepaskan: 2024-11-14 16:44:02
asal
389 orang telah melayarinya

How to Pass a Boost::function to a Method Expecting a Function Pointer?

Deriving a Plain Function Pointer from Boost::function

In some scenarios, it may be necessary to pass a Boost::function to a method that anticipates a standard function pointer (demonstrating the same signature). This can lead to compilation errors.

Conversion Errors

typedef void TriggerProc_type(Variable*, void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)>& triggerProc ...
InitVariable(triggerProc);

// Error: cannot convert parameter 1
Salin selepas log masuk

Avoiding Boost::function

Eliminating Boost::function and referencing the bound functor immediately leads to analogous errors:

error C2664: 'blah(void (__cdecl *)(type *,void *))' : cannot convert parameter
1 from 'boost::_bi::bind_t<R,F,L>&gt;' to 'void (__cdecl *)(type *,void *)'
Salin selepas log masuk

Proposed Solution

The commonly accepted solution is limited as it only operates successfully in trivial cases. A more effective approach involves employing a shim function, which abides by the callback signature, ascertains the applicable Boost::function to invoke, and executes it.

typedef void (*CallbackType)(int x, void* user_data);
void RegisterCallback(CallbackType cb, void* user_data);

void MyCallback(int x, void* userData) {
  boost::function<void(int)> pfn = static_cast<boost::function<void(int)> &>(userData);
  pfn(x);
}

boost::function<void(int)> fn = boost::bind(myFunction(5));
RegisterCallback(MyCallback, &fn);
Salin selepas log masuk

This method ensures compatibility between Boost::function and Boost::bind, enabling their seamless integration with C callbacks. However, if the callback signature lacks a user data pointer, this approach becomes infeasible. Nonetheless, such callback structures are inherently limited in practical applications and warrant revision.

Atas ialah kandungan terperinci Bagaimana untuk Melepasi Boost::function kepada Kaedah Menjangkakan Penunjuk Fungsi?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan