Accessing public class memory from C++ using C

后端 未结 5 519
旧巷少年郎
旧巷少年郎 2021-01-24 22:27

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

相关标签:
5条回答
  • 2021-01-24 22:44

    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,

    0 讨论(0)
  • 2021-01-24 22:45

    The code you posted appears to be OK - you'll need to give more detail if you want the problem debugged. Actually, if you run the program in a debugger, it should be able to tell you exactly which line of code is causing the exception (you may have to look in a call stack), or simply step through the program until it crashes.

    As for the confusion about whether vector can be treated as a C array, it definitely can by getting the address of the first element (ie., &vect[0]) - if the vector contains elements.

    The C++03 standard says this about vector<> in 23.2.4:

    The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()

    Note that this was not explicitly stated in the C++98 standard (but was still the intent).

    See also Herb Sutter's article:

    • http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/

    Note that vector<bool> cannot be treated as a C array - it a special case since the elements in vector<bool> are not stored as bool.

    0 讨论(0)
  • 2021-01-24 22:57

    You can't do that. Vector class is not the same as a C-like array.

    You must convert it to a regular C array before passing it to CFE function.

    Edit: Apparently my answer is wrong. Check Neil's post.

    0 讨论(0)
  • 2021-01-24 22:57

    What's the content of CFE() ?

    Why not define CFE() as; void CFE(float *density, float *energy, int NumElem);

    So you don't have to fool around with casts and just do; density[i] = ... inside your loops?

    0 讨论(0)
  • 2021-01-24 23:02

    The code that you've posted is correct. Provided that every access to an array element inside of CFE() is within bounds, you shouldn't be getting a segmentation fault. Try running your program under valgrind and see if it reports anything unusual.

    0 讨论(0)
提交回复
热议问题