问题描述
我有一个在 VS2008 中创建的 C 应用程序.我正在创建一个模拟创建函数,它覆盖结构中的函数引用.但是,如果我尝试以直接的方式执行此操作,例如:
I have a C application that I've created in VS2008. I am creating a mock creation function that overrides function references in a struct. However if I try and do this in a straight forward fashion with something like:
void *ptr = &(*env)->GetVersion;
*ptr = <address of new function>
然后我收到错误 C2100:非法间接引用"错误为 *ptr,当 ptr 为空时 * 似乎是一个被禁止的构造.我也可以通过使用 int/long 指针来绕过它,将其映射到相同的地址并修改长指针的内容:
then I get a "error C2100: illegal indirection" error as *ptr, when ptr is a void * seems to be a banned construct. I can get around it by using a int/long pointer as well, mapping that to the same address and modifying the contents of the long pointer:
*structOffsetPointer = &(*env)->GetVersion;
functionPointer = thisGetVersion;
structOffsetPointerAsLong = (long *)structOffsetPointer;
*structOffsetPointerAsLong = (long)functionPointer;
但我担心如果我在 32 位和 64 位环境之间切换,使用 long 或 int 指针会导致问题.
but I am concerned that using long or int pointers will cause problems if I switch between 32 and 64 bit environments.
那么有没有简单的方法可以禁用此错误?假设不是,win64下是int还是long 64位?
So is there are easy way to disable this error? Assuming not, is either int or long 64 bits under win64?
推荐答案
那怎么样:
void **ptr = (void **) &(*env)->GetVersion;
*ptr = <address of new function>
正确的方法是使用类型系统,避免所有的转换并声明指向函数的实际指针,例如:
The right way to do this is to work with the type system, avoid all the casting and declare actual pointers to functions like:
typedef int (*fncPtr)(void);
fncPtr *ptr = &(*env)->GetVersion;
*ptr = NewFunction;
以上假设 GetVersion 的类型为 fncPtr 并且 NewFunction 声明为int NewFunction(void);
The above assumes GetVersion is of type fncPtr and NewFunction is declared as int NewFunction(void);
这篇关于如何克服“错误 C2100:非法间接访问"?在 VS2008 中访问 void* 的内容时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!