[英]Are there any pitfalls when calling functions from a C library in a C++ program?
我正在使用在C ++程序中同時具有C接口和C ++接口的庫。 C ++有點不成熟,我必須堅持使用C ++。 我想知道,更籠統地說,在將C樣式的二進制對象文件與C ++項目混合時,有什么要記住的特定事項嗎?
為了從C ++中調用C函數,必須將它們聲明為extern "C"
。 通常在標頭中使用如下所示的內容:
#if defined(__cplusplus)
extern "C" {
#endif
void f();
void g();
#if defined(__cplusplus)
}
#endif
C函數必須聲明為extern“ C”,如果您的C頭文件沒有自動執行此操作,則可以對整個頭文件執行以下操作:
extern "C"
{
#include "c-library.h"
}
否則,只要您對所有內容都使用C ++鏈接器就可以了:)。
RAII是處理來自C ++的C庫時非常有用的一件事。 假設您的C庫具有初始化和發布功能,則可以輕松地將其包裝到資源管理類中:
#include <boost/utility.hpp>
/// Base class for top-level library objects
class lib_base: boost::noncopyable
{
protected:
lib_base()
{
if ( my_c_lib_init() == -1 )
throw std::runtime_error( "no C lib" );
}
~lib_base() { my_c_lib_fini(); }
};
/// Widget from C library
class widget: lib_base
{
public:
widget( const std::string& name ) :
lib_base(), pcw_()
{
if (( pcw_ = my_c_lib_alloc_widget( name.c_str())) == NULL )
throw std::runtime_error( "no more widgets" );
}
~widget() { my_c_lib_release_widget( pcw_ ); }
private:
c_widget* pcw_; //< low-level widget
};
當然,這會使子類不可復制,但是可以通過包含和/或智能指針來解決。
從C ++程序調用C函數非常普遍。 要記住的只有一件事-使用C ++鏈接器:)也要記住C函數不能使用異常,因此您必須檢查它們的返回值。
編輯:其他人指出,C函數聲明應該用extern "C" {...}
包裝。 通常,這已經在庫頭文件中完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.