如何在C结构中获得字段访问回调? [英] How do I get a field access callback inside a C struct?

查看:68
本文介绍了如何在C结构中获得字段访问回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个结构:



Suppose we have a struct:

struct Foo
{
    void(*Print)(); //could be any method pointer
    int MyField;
}





我们可以设置Foo->打印到任何功能,例如:

Foo - > Print = Test;





We can set Foo->Print to any function eg:
Foo->Print = Test;

void Test()
{
   printf("print called");
}

void Callback()
{
   //this should be called for every memory access at Foo->Print
}





如何实现内存访问回调,以便每次调用Foo-> Print时,也会调用Callback?

内存分析器和调试器可以这样做应该是可能的。

如果这对于读取和写入的 MyField 这样的简单字段也适用,那就太好了。 />


我尝试了什么:



我不知道从哪里开始 - 。 -



How do I implement a memory access callback so that every time Foo->Print is called, Callback also is invoked?
Memory profilers and debuggers can do exactly this so it should be possible.
It would be nice if this also works for simple fields like MyField for read and write.

What I have tried:

I dont know where to start -.-

推荐答案

调试器使用特殊指令和操作系统服务来完成此任务。如果你想保持独立于处理器和操作系统,你的选择会受到更多限制。



实现这个的一种方法是引入第二个函数指针;我们称之为PrintWrapper。外面的世界应该只调用PrintWrapper。在此函数中,您可以调用Print并调用Callback(或直接在PrintWrapper中执行Callback的所有任务)。这是一种独立于平台的方式,非常简单。
Debuggers use special instructions and operating system services to accomplish this. If you want to remain independent of the processor and operating system your choices are much more limited.

One way of implementing this is to introduce a second function pointer; let's call it PrintWrapper. The outside world should only call PrintWrapper. And in this function you call Print and call Callback (or do all those task of Callback directly in PrintWrapper). That is a platform independent way of doing it and really simple.


这篇关于如何在C结构中获得字段访问回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆