我的目的是從我的C++代碼調用一些C函數並傳遞一些C++對象。 其實我使用從GSL libray(用C語言編寫)一個集成常規,看到這個link,這個C回調是否安全使用C++對象?
我的代碼片段:
// main.cpp
#include <stdio.h>
#include <gsl/gsl_integration.h>
#include <myclass.h>
/* my test function. */
double testfunction (double x , void *param) {
myclass *bar=static_cast<myclass*>(param);
/*** do something with x and bar***/
return val;
}
int main (int argc , char *argv[]) {
gsl_function F; // defined in GSL: double (* function) (double x, void * params)
/* initialize.*/
gsl_integration_cquad_workspace *ws =
gsl_integration_cquad_workspace_alloc(200) ;
/* Prepare test function. */
myclass foo{}; // call myclass constructor
F.function = &testfunction;
F.params = &foo;
/* Call the routine. */
gsl_integration_cquad(&F, 0.0,1.0,1.0e-10,1.0e-10,ws, &res,&abserr,&neval);
/* Free the workspace. */
gsl_integration_cquad_workspace_free(ws);
return 0;
}
在我的情況下,直接調用gsl_integration_cquad看起來不錯,但所提供的頭文件包含諸如「ifdef __cplusplus」,我的擔心是關於回調F,最初在C中定義的,我是否允許以這種方式通過測試函數和C++ foo對象? 。
還是有沒有更好的方法來做這種東西,也許重載和使用函數?
P.S.我是否允許在回調函數中執行exeption處理? (使用try catch在「testfunction」中)。它適用於我的情況,但不確定它是否合法。
您方式足夠好 - 沒有限制讓事情變得不必要的複雜。你可以以任何方式混合使用c和C++,只要你的鏈接器管理來構建最終的可執行文件或共享對象。 – lowtech 2014-11-06 19:12:51
簡短的回答是肯定的,這很好。但是,我會在'testfunction'的聲明中加入'__cdecl',以防萬一它不是給定平臺的默認值。 – Cameron 2014-11-06 19:18:03
@lowtech謝謝,無論如何,我經常聽說混合C和C++導致問題... – lorniper 2014-11-06 19:18:20