简体   繁体   English

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

[英]C++ Any pointer as function argument

Here are some sample classes to reproduce the situation I'm facing: 以下是一些示例类来重现我所面临的情况:

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'

I know it can be fixed easily with: 我知道可以使用以下方法轻松修复它:

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

but this is not satisfying enough, since it lowers code readability and it's just ugly. 但这还不能令人满意,因为它降低了代码的可读性,而且很丑陋。 I really don't want to use templates since they're already everywhere all over my code. 我真的不想使用模板,因为它们在我的代码中已经无处不在。 Is there any simple container for such variables? 是否有用于此类变量的简单容器? Or some more elegant way of doing it? 还是一些更优雅的方式呢?

EDIT: I've re-adapted question, sorry 编辑:我已经重新适应了问题,对不起

You are using one int* since your function wait for uintptr_t . 您正在使用一个int*因为您的函数等待uintptr_t One is signed, the other is unsigned. 一个是签名的,另一个是未签名的。

Try to use unsigned instead of int or try to use std::intptr_t instead of std::uintptr_t 尝试使用unsigned代替int或尝试使用std::intptr_t代替std::uintptr_t

EDIT : A way to solve your problem could be something like that : 编辑:一种解决您的问题的方法可能是这样的:

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

After, you can do something like : Read(*objA.second, ...); 之后,您可以执行类似以下操作: Read(*objA.second, ...);

The answer from Jarod42 can be good as well ! Jarod42的答案也可能很好!

You might use overload to do the conversion at one place 您可能会使用重载在一处进行转换

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

I suppose you could use a void pointer as an argument.For example: 我想您可以将void指针用作参数,例如:

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

But you should probably pass an other argument to the function in order to determine the type that you should cast the address variable to.So for example: 但是您可能应该将另一个参数传递给函数,以确定应将地址变量转换为的类型,例如:

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