Andrew G
Andrew G

Reputation: 1557

C within C++ code

I have written a C++ application and within it, I need to call a math function that was written in C. The prototype looks like:

void Jacobi_Cyclic_Method(double *eigenvalues, double *eigenvectors, double *A, int n);

My problem is that I can't seem to pass the function double * (for instance both eigenvectors and A are multi-dimensional arrays. The C++ way to pass those things seems to be

double [][size]

I have read about extern C but I don't think it applies here since I am not interfacing with an object but with source itself. How can I send that C function my multi-dimensional arrays defined as such:

double [100][100] A;
double [100][100] eigenvectors;
double [100] eigenvalues;

Trying to compile I get:

error: no matching function for call to ‘MathEngine::Jacobi_Cyclic_Method(double 
[100], double [100][100], double [100][100], int)’
mathEngine.h:9: note: candidates are: static void    
MathEngine::Jacobi_Cyclic_Method(double*, double*, double*, int)

Upvotes: 0

Views: 320

Answers (2)

Michael Wild
Michael Wild

Reputation: 26381

Probably the problem is that your Jacobi_Cyclic_Method function requires the matrix to be in either column or row major format, where every column/row is stored consecutively in a single, one-dimensional array. E.g. for a row major matrix of size m x n, the elements in any given row are stored contiguously and the item in row i and column j would be at position i*n+j (for zero-based indices i and j). If the matrix is column-major, it would be at position i+j*m.

Using multi-dimensional arrays in C/C++ is often not what you want because something like

double A[100][100];

is not a two-dimensional array, but a single array of length 100 containing pointers to arrays of length 100. Consequently, the rows in A are not stored contiguously.

Upvotes: 1

Sean
Sean

Reputation: 5490

I'm assuming that your C function requires multi-dimensional arrays for some of its parameters and that the prototype is written with pointers to doubles for the array/matrix parameters where the integer parameter indicates the size of each dimension (I guess the matrices are square?). If this is the case then you can pass a pointer to the first element of each array/matrix like this:

Jacobi_Cyclic_Methods(&eigenvalues[0], &eigenvectors[0][0], &A[0][0], 100);

Your initial attempt doesn't work because the type of, for instance, eigenvectors is double[100][100] which decays to double (*)[100], not double *.

This post addresses the issue of pointers and multi-dimensional arrays.

Upvotes: 0

Related Questions