结构指针函数指向其他结构的其他函数
struct pointer function points to other function of other struct
我想知道是否可以将其他结构的函数指向一个结构:
示例:
typedef struct
{
int func(int z)
{
return z * 2;
}
} sta;
typedef struct
{
int(*this.func)(int);
} stah;
int main()
{
sta sa;
stah sah;
sah.func = &sa.func;
return 0;
}
这可能在结构中吗?
func
的声明应该如下所示:
int(sta::*func)(int);
或者,或者:
using my_type = int(sta::*)(int);
my_type func;
这更容易阅读:my_type
是类型 的别名,它指向 sta
的成员函数,它获得 int
和 returns一个int
.
func
只不过是一个类型为 my_type
.
的数据成员
为了将指向成员函数的实际指针分配给 func
,您可以这样做:
sah.func = &sta::func;
然后您可以按如下方式调用它:
(sa.*sah.func)(0);
指向方法的指针的正确语法是:
&T::f
其中 T
是声明方法 f
的类型。注意要被调用,指针必须绑定到T
的一个实例,因为指针的值表示到内存中实例开始的偏移量。
在C++14中,你可以考虑std::function
:
#include <functional>
struct sta
{
int func(int z)
{
return z * 2;
}
};
struct stah
{
std::function<int(int)> func;
};
int main()
{
sta sa;
stah sah;
sah.func = std::bind(&sta::func, &sa, std::placeholders::_1);
return 0;
}
您也可以使用 lambda 代替 std::bind
:
int main()
{
sta sa;
stah sah;
sah.func = [&sa](int z) { return sa.func(z); };
return 0;
}
参见 cppreference.com 上的 std::function
, std::bind
, and std::placeholders
。
经过反复尝试,解决方案是这样的:
示例:
typedef struct
{
int a;
int SomeFunc(int a)
{
return a * 4;
}
} somst;
typedef struct
{
int a;
int (*HGetValX)(int);
} hst;
int main()
{
hst* a;
hst decfunc; // New instance
somst b;
decfunc.HGetValX = (int(*)(int))0x421C10; // memory address, or &b.SomeFunc; | &b.SomeFunc; Produces warnings.
b.a = 20;
a = (hst*)&b;
cout << decfunc.HGetValX(4) << b.SomeFunc(4) << a->a << endl;
return 0;
}
查找内存地址
然后代码在没有警告的情况下编译,objective 是用它们的函数挂钩结构。
我想知道是否可以将其他结构的函数指向一个结构:
示例:
typedef struct
{
int func(int z)
{
return z * 2;
}
} sta;
typedef struct
{
int(*this.func)(int);
} stah;
int main()
{
sta sa;
stah sah;
sah.func = &sa.func;
return 0;
}
这可能在结构中吗?
func
的声明应该如下所示:
int(sta::*func)(int);
或者,或者:
using my_type = int(sta::*)(int);
my_type func;
这更容易阅读:my_type
是类型 的别名,它指向 sta
的成员函数,它获得 int
和 returns一个int
.
func
只不过是一个类型为 my_type
.
为了将指向成员函数的实际指针分配给 func
,您可以这样做:
sah.func = &sta::func;
然后您可以按如下方式调用它:
(sa.*sah.func)(0);
指向方法的指针的正确语法是:
&T::f
其中 T
是声明方法 f
的类型。注意要被调用,指针必须绑定到T
的一个实例,因为指针的值表示到内存中实例开始的偏移量。
在C++14中,你可以考虑std::function
:
#include <functional>
struct sta
{
int func(int z)
{
return z * 2;
}
};
struct stah
{
std::function<int(int)> func;
};
int main()
{
sta sa;
stah sah;
sah.func = std::bind(&sta::func, &sa, std::placeholders::_1);
return 0;
}
您也可以使用 lambda 代替 std::bind
:
int main()
{
sta sa;
stah sah;
sah.func = [&sa](int z) { return sa.func(z); };
return 0;
}
参见 cppreference.com 上的 std::function
, std::bind
, and std::placeholders
。
经过反复尝试,解决方案是这样的:
示例:
typedef struct
{
int a;
int SomeFunc(int a)
{
return a * 4;
}
} somst;
typedef struct
{
int a;
int (*HGetValX)(int);
} hst;
int main()
{
hst* a;
hst decfunc; // New instance
somst b;
decfunc.HGetValX = (int(*)(int))0x421C10; // memory address, or &b.SomeFunc; | &b.SomeFunc; Produces warnings.
b.a = 20;
a = (hst*)&b;
cout << decfunc.HGetValX(4) << b.SomeFunc(4) << a->a << endl;
return 0;
}
查找内存地址