繁体   English   中英

C ++任何指针作为函数参数

[英]C++ Any pointer as function argument

以下是一些示例类来重现我所面临的情况:

class A {
B* seccond;
}
class B {
int * number;
}
static NTSTATUS Read(std::uintptr_t address, size_t size, PVOID buff);

// Let's assume we have object 'obj' which has valid address of number variable

int buff;
Read(obj.seccond, sizeof(int), &buff);

Error:  cannot convert argument 1 from 'int *' to 'uintptr_t'

我知道可以使用以下方法轻松修复它:

Read(std::uintptr_t(obj.seccond), sizeof(int), &buff);

但这还不能令人满意,因为它降低了代码的可读性,而且很丑陋。 我真的不想使用模板,因为它们在我的代码中已经无处不在。 是否有用于此类变量的简单容器? 还是一些更优雅的方式呢?

编辑:我已经重新适应了问题,对不起

您正在使用一个int*因为您的函数等待uintptr_t 一个是签名的,另一个是未签名的。

尝试使用unsigned代替int或尝试使用std::intptr_t代替std::uintptr_t

编辑:一种解决您的问题的方法可能是这样的:

class B {
    int *number;
    operator int*() {
        return number;
    }
};

之后,您可以执行类似以下操作: Read(*objA.second, ...);

Jarod42的答案也可能很好!

您可能会使用重载在一处进行转换

static NTSTATUS Read(const void* p, size_t size, PVOID buff)
{
    return Read(std::uintptr_t(p), size, buff);
}

我想您可以将void指针用作参数,例如:

static NTSTATUS Read(void* address, size_t size, PVOID buff);

但是您可能应该将另一个参数传递给函数,以确定应将地址变量转换为的类型,例如:

static NTSTATUS Read(void* address,unsigned code, size_t size, PVOID buff)
{
     //code could be int=1,float=2,...
     switch(code)
     {
         //handle each case int,float,custom type ...
         //by casting the address to the corresponding type(code)
     }
}

暂无
暂无

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

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