【发布时间】:2018-06-15 18:04:03
【问题描述】:
我有一个第 3 方 API,它有一个函数,该函数将函数指针作为参数(示例类型):
// defined in "Api.h"
typedef int (*Callback) (int x);
unsigned char ApiCall(int p, Callback cb);
int ApiCall(int p, Callback cb) {
return cb(p);
}
我正在尝试使用类实例方法与此 API 进行交互;这是一个示例类:
class ApiWrapper {
public:
int ApiCallback(int x) { return this->factor_ * x; }
static int WorkingApiCallback(int x) { return 3 * x; }
ApiWrapper(int f) { this->factor_ = f; }
private:
int factor_;
}
还有一个要测试的主要功能:
#include <iostream>
#include <functional>
int main() {
ApiWrapper a(2);
using std::placeholders::_1;
std::function<int(int)> lambda = std::bind( &ApiWrapper::ApiCallback, a, _1 );
std::cout << "Class: " << a.ApiCallback(21) << std::endl;
std::cout << "Lambda: " << lambda(21) << std::endl;
std::cout << "Static ApiCall:" << ApiCall(21, ApiWrapper::WorkingApiCallback) << std::endl;
// NOT WORKING
std::cout << "Static ApiCall:" << ApiCall(21, lambda) << std::endl;
std::cout << "Static ApiCall:" << ApiCall(21, this.ApiCallback) << std::endl;
return 0;
}
有没有办法在不使用static 成员的情况下实现这一点;因为每次第 3 方库调用回调时,我都需要关联/使用状态。
- 在线可运行源:https://ideone.com/7nVSi8
谢谢!
【问题讨论】:
-
指向非
static类方法的指针与类C 函数指针不兼容,因为它们将this指针作为第一个参数传递。 IE。class ApiWrapper { int ApiCallback(int x); };中的方法ApiCallback在内部表示为int ApiCallback (ApiWrapper* this, int x);。现在很明显为什么它与typedef int (*Callback) (int x);不兼容 -
嗯,谢谢你的评论,是的,我想,希望有一个解决方法或者我可能会丢失一些东西,这将迫使我跟踪静态成员内部的状态:(
-
嗯.. 状态需要存储在某个地方,它可以传递给函数(需要一个额外的参数,使签名不同,因此不兼容),或者全局(不需要将其传递给函数 - 不需要更改函数签名)。
-
最后一个你可以像这样调用
std::cout << "Static ApiCall:" << ApiCall(21, ApiWrapper{2}.ApiCallback) << std::endl; -
你确定api回调的x参数是int,而不是void*?