前段時間,碰到了C,C++混合編程的需求,經過努力,順利解決問題.現把這方面的知識做一下簡單的總結:
1.當C++文件要用到C語言中的函數代碼時,采用下屬方法即可:
在C++中的.h文件或.cpp文件中加入下列代碼,
#define LINT_ARGS 1
extern "C" {
#include "system.h"
}
然后在代碼中直接調用這些函數即可.
注解:
1.1 LINT_ARGS 1表示在檢查C語言中的函數原型時,要對函數原型的參數進行檢查.
1.2. "{ }" 中包含的頭文件為C語言中的頭文件.
1.3.extern "C" 告訴鏈接器,這些頭文件中的函數被當做C語言中的函數來處理.
下面以一個實例加以說明:
下面為一個C語言的頭文件(sysgct.h):
#ifdef LINT_ARGS
int GCT_send(unsigned int task_id, HDR *h);
......
#else
int GCT_send();
......
#endif
~
in file MapBaseReq.cpp 文件中
#include ....
extern "C"
{
#include "sysgct.h"
}
void
MapBaseReq::sendPdu(const BasePdu_var& thePduP)
{
...
if (GCT_send(m->hdr.dst, (HDR *)m) != 0)
{
relm((HDR *)m);
SETERR1(errSWErrorMsg, "sendPdu(): GCT_send() Failed");
}
...
}
2.當C文件要用到C++語言某個類中的方法時,可以采用下列方法:
2.1 在cpp文件中用下列方式定義函數:
extern "C" returnType FunName(parameters list).
2.2 然后在相應的頭文件中進行聲明:
extern returnType FunName(parameters list);
2.3 在相應的.c文件中包含該頭文件,然后直接利用相應的函數即可.
下面給出實例.
2.4 cpp文件
#include <iostream>
#include <iomanip>
#include "TTDebug.h"
using namespace std;
extern "C"
{
#include "Utility.h"
}
static int display_hex_buffer(unsigned char* buffer, unsigned char* ptr,int len);
extern "C" void tDebug_traceFunc(int level, char* trace)
{
TDEBUG_TRACEFUNC(level,trace);
}
extern "C" void nDebug(int level, unsigned char* args, int iLen, int cid)
{
unsigned char buf[512];
if(0 != TTDebug::instance() && TTDebug::instance()->isTTDebugOn(level))
{
/* Check whether the current thread already holds the mutex lock */
LockGuard<MutexWrapper> guard(TTDebug::instance()->mutex());
TTDebug::instance()->traceStart(level, __FILE__, __LINE__);
memset(buf,0,512);
display_hex_buffer(buf,args,iLen);
TTDebug::instance()->outStream() << "Send Msg(0-0x" << setw(4) << setfill('0') << hex << cid <<"):0x" << buf;
TTDebug::instance()->traceEnd();
}
}
2.5 .h 文件
#ifndef __UTILITY_H
#define __UTILITY_H
extern void tDebug_traceFunc(int level, char* trace);
extern void nDebug(int level, unsigned char* args,int iLen, int cid);
#endif
2.6 cpp文件中定義的函數在c文件中調用實例
在test.c文件中:
...
int ctu_ent(msg,pInt)
MSG* msg;
int *pInt;
{
tDebug_traceFunc(10,"ctu ctu_ent");
HDR *h;
MSG *m;
...
}
...