简体   繁体   English

如何包装C ++函数?

[英]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: 通过遵循教程,我试图包装一个名为i_receive()c++函数,我首先创建了wrap.c文件,该文件的内容如下所示:

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: 当我使用LD_PRELOADLD_PRELOAD=/full/path/to/wrap.so ./mycppcode运行某些C ++代码时,我使用gcc -fPIC -shared -o wrap.so wrap.c -ldl编译了此文件。信息:

ERROR: ld.so: object '/full/path/to/wrap.so' from LD_PRELOAD cannot be preloaded: ignored`. 错误:ld.so:无法预加载来自LD_PRELOAD的对象'/full/path/to/wrap.so':已忽略。

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? 我猜测原因可能是包装文件是C文件,并且我将其与C ++代码一起使用,对吗?

I changed the file to wrap.cc with the same content, when compiling in the same way as before, I got: 我将文件更改为具有相同内容的wrap.cc ,以与以前相同的方式编译时,我得到:

ERROR: invalid conversion from 'int (*)(const uint32_t*, int32_t)' to 'int' 错误:从'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. 实际上,函数的返回类型为int但您正在返回函数指针。

First of all, your 2nd error your are getting becase you are returning a Pointer to function type instead of a int type. 首先,您遇到的第二个错误是您将指针返回给函数类型而不是int类型。

If you want to return an int, call the function from the code : 如果要返回一个int,请从代码中调用该函数:

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. 关于您的猜测:无论您使用的是C还是C ++代码,这些库都是汇编代码。

One difference between exporting C functions and C++ functions is the name mangling. 导出C函数和C ++函数之间的区别是名称修改。 You would rather export a function as a C function to be able to access it inside your library through unmagled name. 您宁愿将函数导出为C函数,以便能够通过未修饰的名称在库中访问它。

To export a function without name mangling it, you can use extern "C" . 要导出不带名称修饰功能的函数,可以使用extern“ C”。

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

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