简体   繁体   English

将 C++ 成员函数传递给 C 函数

[英]Pass a C++ member function to a C function

We have a structure that accepts C function pointers:我们有一个接受 C 函数指针的结构:

int one(int x)
{
}

int two(int x)
{
}

struct Cstruct
{
    int (*fn1)(int);
    int (*fn2)(int);
};

Now I have a C++ class that has below methods:现在我有一个 C++ 类,它具有以下方法:

class A
{
public:
    int one(int x)
    {
    }

    int two(int x)
    {
    }

    int three(int x)
    {
        struct Cstruct cstr = {&this->one, &this->two};
    }
};

While trying to initialize class A methods address to a instance of Cstruct compiler is giving error of an invalid conversion?在尝试将 A 类方法地址初始化到 Cstruct 编译器的实例时,是否给出了无效转换的错误?

How can I assign the Class member function address to Cstruct?如何将 Class 成员函数地址分配给 Cstruct?

You cannot do it, because C++ pointer to a non-static member function is not compatible with a non-member function pointer type.您不能这样做,因为指向非静态成员函数的 C++ 指针与非成员函数指针类型不兼容。 This is because member functions require an additional argument - the object on which the member function needs to be called, which becomes this pointer inside the invocation.这是因为成员函数需要一个额外的参数 - 需要调用成员函数的对象,它在调用中成为this指针。

If you make your member functions static, your code would compile.如果你让你的成员函数是静态的,你的代码就会编译。 However, it would not necessarily do what you want to achieve, because one and two have no access to other non-static members of A .但是,它不一定会执行您想要实现的目标,因为onetwo无法访问A其他非静态成员。

A trick to passing member functions to C functions requires passing an additional void* pointer with the "registration" record, and having C code pass it back to your static callback functions:将成员函数传递给 C 函数的技巧需要传递一个带有“注册”记录的额外void*指针,并让 C 代码将其传递回您的静态回调函数:

struct Cstruct
{
    void *context; // Add this field
    int (*fn1)(void*, int);
    int (*fn2)(void*, int);
};

class A
{
public:
    static int oneWrap(void* ptr, int x)
    {
        return static_cast<A*>(ptr)->one(x);
    }

    static int twoWrap(void* ptr, int x)
    {
        return static_cast<A*>(ptr)->two(x);
    }

    int one(int x)
    {
    }

    int two(int x)
    {
    }

    int three(int x)
    {
        struct Cstruct cstr = {this, &this->oneWrap, &this->twoWrap};
    }
};

C code would need to pass the value of context to fn1 and fn2 : C 代码需要将context的值传递给fn1fn2

cs.fn1(cs.context, 123);
cs.fn2(cs.context, 456);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM