我假设closure 参数是一个上下文“cookie”,用于使用回调获取适当的上下文。这是回调函数的一个惯用语,根据您提供的 sn-ps 似乎是正在发生的事情(但我不确定,因为我对kcache_create() 一无所知,除了你在这里发布)。
您可以使用该 cookie 将指针传递给您正在处理的 cls_lasvm 实例,如下所示:
extern "C"
double
lasvm_kcache_create_callback( int i, int j, void* closure)
{
// have to get a cls_lasvm pointer somehow, maybe the
// void* clpsure is a context value that can hold the
// this pointer - I don't know
cls_lasvm* me = reinterpret_cast<cls_lasvm*>( closure);
return me->kernel( i, j)
}
class cls_lasvm //...
{
...
// the callback that's in the class doens't need kparam
double cls_lasvm::kernel(int i, int j);
};
...
// called like so, assuming it's being called from a cls_lasvm
// member function
lasvm_kcache_t *kcache=lasvm_kcache_create(&lasvm_kcache_create_callback, this);
如果我错认为闭包是上下文 cookie,那么您在 cls_lasvm 类中的回调函数需要是静态的:
extern "C"
double
lasvm_kcache_create_callback( int i, int j, void* closure)
{
// if there is no context provided (or needed) then
// all you need is a static function in cls_lasvm
return cls_lasvm::kernel( i, j, closure);
}
// the callback that's in the class needs to be static
static double cls_lasvm::kernel(int i, int j, void* closure);
请注意,在 C++ 中实现的 C 回调函数必须为extern "C"。它可能看起来像一个类中的静态函数,因为类静态函数通常使用与 C 函数相同的调用约定。但是,这样做是一个等待发生的错误(请参阅下面的 cmets),所以请不要 - 改为使用 extern "C" 包装器。
如果closure 不是上下文cookie,并且由于某种原因cls_lasvm::kernel() 不能是静态的,那么您需要想出一种方法将this 指针存储在某处并在@987654332 中检索该指针@函数,类似于我在第一个示例中所做的方式,只是指针必须来自您自己设计的某种机制。请注意,这可能会使使用 lasvm_kcache_create() 不可重入和非线程安全。这可能是也可能不是问题,具体取决于您的具体情况。