简体   繁体   English

从 C 访问内联 C++ function

[英]Access inline C++ function from C

I'm trying to create C funciton wrappers for C++ and my goal is to make them inline.我正在尝试为 C++ 创建 C 函数包装器,我的目标是使它们内联。 All the solutions on the inte.net say that when making an inline function in a library, just put the function definition in the header file. inte.net 上的所有解决方案都说,在库中制作内联 function 时,只需将 function 定义放入 header 文件中即可。 This won't work in this case though, since the functions contain code that will only compile in C++.但这在这种情况下不起作用,因为函数包含的代码只能在 C++ 中编译。

This example demonstrates the situation:这个例子演示了这种情况:

// box_c.cpp
#include "box.h"

extern "C" Square *new_Square(int width, int height){
    return new Square(width, height);
}



// box_c.h
void *new_Square(int width, int height);



// main.c
#include "box_c.h"

int main(void){
    void *s = new_Square(5, 5);
}


Wold it be possible to make new_Square inline in this case?在这种情况下是否可以使new_Square内联? (The wrapper is a static library). (包装器是一个 static 库)。

Inlining means the compiler of the source where it is inlined needs to understand it on some level.内联意味着内联源代码的编译器需要在某种程度上理解它。 C compilers don't understand C++ new . C 编译器不理解 C++ new . You can't do this.你不能这样做。 Leave it non-inlined, so a compiled version of the code can be linked without the compiler needing to understand C++ natively.让它保持非内联,这样就可以链接代码的编译版本,而无需编译器本身理解 C++。

If the code (both library and final executable) is compiled with LTO enabled, it's possible the linker might inline the code at that point, but there are no guarantees there.如果代码(库和最终可执行文件)是在启用 LTO 的情况下编译的,则 linker 可能会在此时内联代码,但并不能保证。

Obviously in general you cannot inline C++ code inside C code, they are two different languages.显然,通常你不能在 C 代码中内联 C++ 代码,它们是两种不同的语言。

So, either所以,要么

  • force the explicit instantiation of the C++ function in the compiled library,在编译库中强制显式实例化 C++ function,

  • ensure that the C++ function is code-compatible with C and leave it in the header file as inline.确保 C++ function 与 C 代码兼容,并将其作为内联保留在 header 文件中。

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

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