您的位置:首页 > 编程语言 > C语言/C++

写C/C++兼容的代码

2011-12-04 11:49 302 查看
>> 使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: