简体   繁体   English

如何从返回类型未知的函数中获取 c/c++ 中的字节数组?

[英]How to get a byte array in c/c++ from a function with unknown return type?

For example, I know the address of the function (lets say its 0x0183ad0 ), and I would like to get an object from that function which returns an unknown type:例如,我知道函数的地址(假设它是0x0183ad0 ),我想从该函数中获取一个返回未知类型的对象:

unknownType(*fname)() = (unknownType(*)())0x0183ad0

Is there any global type I can replace unknownType with or any method to get that object as a byte array (I know the sizeof(unknownType) )是否有任何全局类型可以替换unknownType或任何方法将该对象作为字节数组(我知道sizeof(unknownType)

NOTE:笔记:

The function return an object NOT A POINTER该函数返回一个对象 NOT A POINTER


EDIT:编辑:

It worked thanks to Botje's answer:由于 Botje 的回答,它起作用了: 回答

"byte array" would be uint8_t* or unsigned char* . “字节数组”将是uint8_t*unsigned char*

If you know the size of unknownType I would create a如果你知道unknownType的大小,我会创建一个

struct unknownType {
    uint8_t stuff[123];
};

so you can adapt the struct definition as you gain better understanding of its fields.因此,您可以在更好地了解其字段时调整结构定义。

You could define a void function pointer and use that prototype for each of the functions that you have the address of: The return value in this example is to aa RANDOM STRUCTURE it could be the whole array of whatever you want bytes, ints, chars- This could of course be different for each function called, as long as the function signature was the same (you could always add a void pointer on the parameter list if they need different input)您可以定义一个 void 函数指针并为您拥有地址的每个函数使用该原型: 本示例中的返回值是一个随机结构,它可以是您想要的任何字节、整数、字符的整个数组-这对于每个调用的函数当然可能不同,只要函数签名是相同的(如果它们需要不同的输入,你总是可以在参数列表上添加一个空指针)

#include <stdio.h>

typedef struct _RANDSTRUCT 
{
    int Num ;
} RANDSTRUCT ;

typedef void * UNKNOWNFUNC (void) ;

UNKNOWNFUNC *myFunc() ;

int main()
{
    void *retP ;
    UNKNOWNFUNC *fnP ;
    
    retP = myFunc () ;

    printf ("Num %d (direct call)\n", ((RANDSTRUCT *)retP)->Num) ;

    fnP = (void *)&myFunc ;
    retP = fnP () ;
    
    printf ("Num %d (fn addr call)\n", ((RANDSTRUCT *)retP)->Num) ;
    
    return 0;
}

UNKNOWNFUNC *myFunc () {
    static RANDSTRUCT randstruct[2] = {100, 200} ;
    
    return ((void *)&randstruct[0]) ;
}

How to get a byte array in c/c++ from a function with unknown return type?如何从返回类型未知的函数中获取 c/c++ 中的字节数组?

Only way to call a function in C++ is to know its return type.在 C++ 中调用函数的唯一方法是知道它的返回类型。 If you don't know the return type, then you cannot call the function, and as such you cannot get the object returned by the function.如果不知道返回类型,则无法调用该函数,因此无法获取该函数返回的对象。

It worked thanks to Botje's answer多亏了 Botje 的回答,它才奏效

It may look like it works, but the behaviour of the program is undefined.它可能看起来有效,但程序的行为是未定义的。

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

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