Greetings Everyone.
I’m currently writing a multi-language programe in C, C++ and fortran on UNIX, unfortunatly I run into ‘Segmentation Error’ when I try and execute after compiling.
I’ve narrowed down the problem to the interface between the C++ and C sections of my program. The first section consists of main.ccp and SA.cpp, and the second CFE.c.
A class called ‘SimAnneal’ exsists in SA.cpp, with public vectors DensityArray and ElementArray. The order of the program follows:
-
Create SimAnneal Object ‘Obj1’ and call function ObjFunction()
-
That function initializes the vector sizes
-
Call CFE(…) with pointers to both vectors and their length.
-
CFE.c edits the data elements of the vectors directly via use of the pointers
-
ObjFunction() uses EnergyArray (and possible DensityArray) data.
The relevant script is below for all sources:
main.cpp
#include 'SA.h' int main() { SimAnneal Obj1; Obj1.ObjFunction(); return 0; }
SA.h
class SimAnneal { void Initialize (); ... public std::vector<float> DensityArray; std::vector<float> EnergyArray; double ObjFunction (); ... }
SA.cpp
#include 'CFE.h' void SimAnneal::Initialize () { int length = 15; EnergyArray.resize(length); DensityArray.resize(length); } double SimAnneal::ObjFunction () { Initialize (); CFE(&DensityArray[0], &EnergyArray[0], DensityArray.size()); // sends pointers of both arrays to CFE.c, which will then // directly modify the array double SumStrainEnergy = 0; for (int i = 0; i < EnergyArray.size(); i++) { SumStrainEnergy += EnergyArray[i]; //Effectively sum of array //engy[] from CFE.c } return SumStrainEnergy; }
CFE.h
#ifdef __cplusplus extern 'C' { #endif void CFE(float density[], float energy[], int NumElem); #ifdef __cplusplus } #endif
CFE.c
void CFE(float density[], float energy[], int NumElem) { ... float * dens; dens = density; //pass pointer of array density[0] in SA.cpp to CFE.c for(n=0; n<NumElem; n++) { ... modify dens (e.g. DensityArray from SA.cpp) ... } float * engy; engy = energy; //pass pointer of array energy[0] in SA.cpp to CFE.c for(n=0; n<NumElem; n++) { ... modify engy (e.g. EnergyArray from SA.cpp) ... } }
Am I causing an illegal memory access by trying to access the vector elements from the C portion of my program? Is there any sure way to allow this?
Any help would be much appriciated.
Provided you stay within the bounds of the vector, what you are doing would seem to be OK.
You can treat a std::vector exactly as if it were a C array by doing what you are doing – taking the address of the first element. The C++ Standard has been changed to specifically allow this kind of usage.
Can’t find a copy of C++ the Technical Corrigendum 2003 at present, but apparently the relevant section ref is 23.2.4,