更新
我发现如果在构造函数中通过引用传递,则可以解决A.cpp中的问题!
即InfoPass(vector<double> &arg0, vector<double> &arg1...)
,这是什么原因?
更新
基本上我想从c ++调用一些c代码。
如c手册中所述,为避免使用gloabal变量,提供了“ void * fdata”以获取其他信息,如果没有的话,则指向NULL。
int f(unsigned ndim, unsigned npts, const double *x, void *fdata,
unsigned fdim, double *fval);
现在,我需要打包一些c ++对象,并通过* fdata参数传递给“ f”,我想到的方法是定义一个类“ InfoPass”,并将其传递给c例程。
我的C ++代码段(例如A.cpp和B.cpp,A在B正常的情况下无法正常工作):
// Example A.cpp
#include "cubature.h" // the c library called cubature
#include "extern_cpp_class.hpp" //
class InfoPass
{
public:
extern_cpp_class obj1;
extern_cpp_class obj2;
extern_cpp_class obj3;
double arr[3];
InfoPass(vector<double>arg0, vector<double>arg1, vector<double>arg2, vector<double>arg3)
: obj1{arg0, arg1}, obj2{arg0, arg2}, obj3{arg0, arg3} {}
};
// the declaration of int f() and cubature() below are in the c code
int f(unsigned ndim, const double *x, void *fdata, unsigned fdim, double *fval);
int main() {
/*** do something ***/
InfoPass cubpass{arg0, arg1, arg2, arg3}; // initialize
cubature(2, f, &cubpass, 2, xmin, xmax, 1e5, 0, 1e-5, ERROR_PAIRED, OUTPUT, &err);
/*** process with output ***/
}
int f(unsigned ndim, const double *x, void *fdata, unsigned fdim, double *fval)
{
InfoPass *fcubpass=static_cast<InfoPass*>(fdata);
/*** do things with fcubpass.obj1, .obj2 ... ***/
}
现在,我可以编译(gcc)并运行示例A,奇怪的是,存在未定义的行为,有时会给出NaN,有时会给出非常疯狂的数字...
但是,如果我改为按照以下方式操作(示例B,使用指向类的指针),然后在f中使用“ new”,则效果很好!想知道为什么?因为我更喜欢示例A而不是示例B,因此我总是需要“新”东西...
// Example B.cpp
class InfoPass
{
public:
extern_cpp_class *obj1=NULL;
extern_cpp_class *obj2=NULL;
extern_cpp_class *obj3=NULL;
double arr[3];
~InfoPass(){
delete obj1;
delete obj2;
delete obj3;
}
}
int main() {
/*** do something ***/
InfoPass cubpass; // declare
cubpass.obj1 = new extern_cpp_class(arg0,arg1);
cubpass.obj2 = new extern_cpp_class(arg0,arg2);
cubpass.obj3 = new extern_cpp_class(arg0,arg3);
cubature(2, f, &cubpass, 2, xmin, xmax, 1e5, 0, 1e-5, ERROR_PAIRED, OUTPUT, &err);
/*** process with output ***/
}
int f(unsigned ndim, const double *x, void *fdata, unsigned fdim, double *fval)
{
InfoPass *fcubpass=static_cast<InfoPass*>(fdata);
/*** do things with fcubpass->obj1, .obj2 ... ***/
}
这里只是黑暗中的一枪。
extern_cpp_class
对象用其初始化参数做什么?如果它们将vector
参数作为参考并将其存储为引用,则您会遇到麻烦,A.cpp
因为参数是cubpass
构造函数执行完后会被破坏(使引用无效)的临时副本。切换到传递的引用将通过确保extern_cpp_class
对象接收对vector
s的引用来解决此问题,在s中创建的s main
(大概)在程序退出之前(或至少在完成使用之前)一直有效cubpass
。在中B.cpp
,构造函数已经获得了对的引用vector
,因此没有问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句