插入C结构函数指针 [英] Interpose C struct function pointer
问题描述
我正在尝试将声明为指针的函数插入到macOS上的动态库中的C结构中.
i'm trying to interpose function declared as a pointer in a C struct inside dynamic library on macOS.
我在libA.dylib中有这个结构:
I have this struct in libA.dylib:
libA.h:
typedef struct AStruct {
int (*sub)(AStruct *pAStruct, int a, int b);
} AStruct;
extern "C" AStruct * AStruct_new();
libA.cpp:
int sub(AStruct *pAStruct, int a, int b) {
return a - b;
}
AStruct * AStruct_new() {
AStruct *pAStruct = (AStruct *)malloc(sizeof(AStruct));
pAStruct->sub = *sub;
return pAStruct;
}
名称修改后,我发现库中的相应名称是: _Z3subP7AStructii
after name mangling, i've figured out that corresponding name in library is this: _Z3subP7AStructii
在我的 dylib(我将其注入客户端代码)中,我正在这样做:
inside my dylib (which i'm injecting into a client code) i'm doing this:
typedef struct AStruct {
int (*sub)(AStruct *pAStruct, int a, int b);
} AStruct;
extern "C" int _Z3subP7AStructii(AStruct *pAStruct, int a, int b);
int _sub(AStruct *pAStruct, int a, int b) {
printf("interposed %s: ", __func__);
return pAStruct->sub(pAStruct, a, b);
} DYLD_INTERPOSE(_sub, _Z3subP7AStructii)
DYLD_INTERPOSE
-是同一代码可成功用于常规C函数,C ++静态/实例方法,但无法弄清struct:(
the same code successfully works for regular C function, C++ static/instance methods, can't figured out what's wrong with function pointer inside struct :(
推荐答案
如果我理解正确,则您希望对 sub
(或更确切地说是 _Z3subP7AStructii
)的所有调用而是调用您的 _sub
函数?问题在于,当客户端"调用 some_astruct-> sub(...)
时,它实际上并没有直接调用 _Z3subP7AStructii
,因此您的 _sub
函数不会被调用.
If I understand correctly, you want all calls to sub
(or rather _Z3subP7AStructii
) to actually be calling your _sub
function instead? The problem is that when the "client" calls some_astruct->sub(...)
it doesn't actually call _Z3subP7AStructii
directly, and therefore your _sub
function won't be called.
换句话说,客户端"没有调用 _Z3subP7AStructii
,而是调用了 some_astruct-> sub
指向的任何内容.. _Z3subP7AStructii
函数甚至无法通过 libA
库导出(即与例如 static
进行内部链接),并且仍可以通过以下方式调用它:结构.
In other words, the "client" doesn't have a call to _Z3subP7AStructii
, but instead it have a call to whatever some_astruct->sub
is pointing to. The _Z3subP7AStructii
function could even not be exported by the libA
library (i.e. have internal linkage with e.g. static
), and it could still be called through the structure.
对此的可能解决方案不是插入" sub
函数,而是" AStruct_create
"函数.在您的版本中,请调用原始文件,然后将结构中 sub
函数的指针替换为您自己的函数(可以保存原始文件以便使用).
A possible solution to this is not to "interpose" the sub
function, but instead the AStruct_create
function. In your version call the original, then replace the pointer to the sub
function in the structure to your own function (possibly saving the original so you can use it).
这篇关于插入C结构函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!