简体   繁体   English

C / C ++结构问题

[英]C/C++ struct question

Suppose you have a .cpp file (that is, compiled using a C++ compiler like MSVC). 假设您有一个.cpp文件(即使用像MSVC这样的C ++编译器编译)。 In that file, you define a struct in the following way: 在该文件中,您可以通过以下方式定义struct

struct Pixel
{
   float x, y;
};

In the same file, you have a line of code that will call a C function, that requires a C struct equal to Pixel . 在同一个文件中,您有一行代码将调用C函数,它需要一个等于Pixel的C struct If you write: 如果你写:

Pixel my_pixel
// set my_pixel to something
c_func(&my_pixel);

will it work? 它会起作用吗? I mean, the C++ compiler will create the object my_pixel , but it will pass it to a function that is compiled as C code (i have only a .lib of that library). 我的意思是,C ++编译器将创建对象my_pixel ,但它会将它传递给编译为C代码的函数(我只有该库的.lib)。

If the header file is correct, it will work, assuming the C compiler and the C++ compiler use compatible calling conventions. 如果头文件是正确的,它将起作用,假设C编译器和C ++编译器使用兼容的调用约定。 Make sure the header file has an appropriate extern "C" block that contains the function definition. 确保头文件具有包含函数定义的适当的extern "C"块。

The reason David Schzwartz says you need an extern "C" block is that without the extern "C" block, the compiler will "mangle" the name of the C function you are calling at the point you call it. David Schzwartz说你需要一个extern "C"块的原因是,如果没有extern“C”块,编译器将在你调用它的位置“修改”你正在调用的C函数的名称。 If you are calling a C function and not a C++ function, the function's definition in your library will not have a mangled name, so your executable will fail to link. 如果您正在调用C函数而不是C ++函数,则库中函数的定义将不会出现错位,因此您的可执行文件将无法链接。

That's what you want if the function you are calling is written in C++, as name mangling allows for function name overloading. 如果你调用的函数是用C ++编写的,那就是你想要的,因为名称修改允许函数名称重载。 The types of each of a function's parameters are compactly encoded in the mangled function name. 每个函数参数的类型都在受损函数名中紧凑编码。

Name mangling was originally provided in C++ to allow C++ object files to be linked with legacy linkers, rather than having to provide a C++-specialized linker that has explicit support for overloaded functions. 名称mangling最初是用C ++提供的,它允许C ++目标文件与遗留链接器链接,而不是必须提供一个C ++专用链接器,它明确支持重载函数。

C doesn't permit function name overloading, so C function names are never mangled. C不允许函数名重载,因此C函数名永远不会被破坏。 To provide a prototype in C++ for a single C function you do this: 要为单个C函数提供C ++原型,请执行以下操作:

extern "C" Foo( int theInt );

If you have a whole header file full of C function prototypes and you want to #include that header from a C++ source, enclose the #include in an extern C block 如果你有一个完整的C函数原型的头文件,并且你想#include来自C ++源代码的头,那么将#include包含在一个extern C块中

extern "C" {
    #include "Foo.h"
}

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

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