简体   繁体   中英

How to wrap a C++ function?

I'm trying to wrap a c++ function called i_receive() by following this tutorial, I first created a wrap.c file, the content of this file is like this:

int i_receive(const uint32_t *f, int32_t t){

    static int (*real_i_receive)(const uint32_t *, int32_t)=NULL;
    printf("hello world");
    return real_i_receive;
}

I compiled this file with gcc -fPIC -shared -o wrap.so wrap.c -ldl , when I used the LD_PRELOAD to run some C++ code with LD_PRELOAD=/full/path/to/wrap.so ./mycppcode I got this message:

ERROR: ld.so: object '/full/path/to/wrap.so' from LD_PRELOAD cannot be preloaded: ignored`.

I was guessing the reason might be that the wrap file is a C file, and I'm using it with C++ code, am I right?

I changed the file to wrap.cc with the same content, when compiling in the same way as before, I got:

ERROR: invalid conversion from 'int (*)(const uint32_t*, int32_t)' to 'int'

Replace

return real_i_receive;

with

return real_i_receive(f, t);

As it is, the return type of your function is int but you're returning a function pointer.

First of all, your 2nd error your are getting becase you are returning a Pointer to function type instead of a int type.

If you want to return an int, call the function from the code :

return real_i_receive(f,t);

Notice the "()" which means a function call.

Regarding your guess : it doesn't matter if you are using C or C++ code, the libaries are all assembly code.

One difference between exporting C functions and C++ functions is the name mangling. You would rather export a function as a C function to be able to access it inside your library through unmagled name.

To export a function without name mangling it, you can use extern "C" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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