写C/C++兼容的代码

>> 使用extern "c":

C和C++对函数的处理方式并不相同。

利用extern "C", C++能够知道该函数是C链接。因而,如果要对编译器提示使用C的方式来处理函数的话,那么就要使用extern "C"来说明.

C++编译器开发商已经对C 标准库的头文件作了extern“C”处理,所以 我们可以用#include 来直接引用这些头文件。

/* Raw_C_Api.h*/

#define DLL_EXPORT

#ifdef DLL_EXPORT
# define DLL_API _declspec(dllexport)

/* Make sure we can call this stuff from C++.*/
# ifdef __cplusplus
extern "C" {
# endif

#else
# define DLL_API _declspec(dllimport)
#endif

/* C/C++ compatible interface*/
void DLL_API doSomethingWithCPP(char* myChar);

#ifdef DLL_EXPORT
# ifdef __cplusplus
} /* end of the 'extern "C"' block */
# endif
#endif

Implementatioin:

/* Raw_C_Api_ImplByCPP.cpp*/
#include "Raw_C_Api.h"
#include <string>

/* Process raw C String with std::string*/
void doSomethingWithCPP(char* myChar)
{
std::string myString(myChar);
/* TODO: Do More things on myStrig */
}

>>  structure

在C++中,为Structure加上构造函数。

typedef struct _coord_2d {

float x;
float y;

/* define constructors for c++.*/
#if defined(__cplusplus)
inline _coord_2d() {}
inline _coord_2d(const _coord_2d &v) : x(v.x), y(v.y) {}
inline _coord_2d(float x, float y) : x(x), y(y) {}
#endif
} Coord2d;

- Piaoger

 

原文链接: https://www.cnblogs.com/piaoger/archive/2011/12/04/2275304.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    写C/C++兼容的代码

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/37820

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午2:29
下一篇 2023年2月8日 下午2:30

相关推荐