How to convert c++ float* datatype to igraph matrix datatype?

Hello, I got an error when I try to convert c++ float* datatype to igraph_real_t. This is the error I got:

error: cannot convert 'float*' to 'igraph_real_t* {aka double*}' in assignment
matrix_data = data;

The background is I generated an adjacency matrix by using python, and then convert the ndarray to c_char_p datatype, and passing this value to cpp program. The following are my python code:

    lib = ctypes.CDLL('./librunWalktrap.so')
    dataTemp = simlarity_matrix_np.ctypes.data
    dataptr = simlarity_matrix_np.ctypes.data_as(ctypes.c_char_p)
    rows, cols = simlarity_matrix_np.shape
    func_c_walktrap = lib.py2c_walktrap(dataptr, rows, cols)

After I passing my c_char_p which is the adjacency matrix to c++ program, I met a problem about how to use my adjacency matrix to genrate the graph. The following code is what I tried to generate the matrix and graph, but I got the error like I mentioned above:

int py2c_walktrap(float* data, int rows, int cols) {
    igraph_matrix_t m;
    igraph_real_t matrix_data;
    igraph_integer_t nrow;
    igraph_integer_t ncol;
    igraph_matrix_storage_t storage;

    nrow = rows;
    ncol = cols;
    matrix_data = data;
    igraph_matrix_init_array(&m, &matrix_data, nrow, ncol, storage);
}

Do you guys have any idea about what should I do? Thank you very much!

There are multiple problems here:

  1. float is a 4-byte IEEE single-precision representation of a floating-point number, but igraph_real_t is a type alias to a double, which is an 8-byte IEEE double-precision representation. When you assign a float to a double in C/C++, the compiler automatically does the conversion behind the scenes; however, it cannot do this automatically for an array of floats or doubles.

  2. matrix_data as it is declared now is a double-precision IEEE floating-point number, while data is a pointer to an array of single-precision numbers. You cannot assign a whole array of numbers into a single number.

Thank you very much! I will check my code and do some changes, so I should change my float* to double* right?

Yes, and you probably won’t need matrix_data at all. Note that igraph_matrix_init_array() will create a copy of your array; if you don’t want that and your data is in column major format, you can use igraph_matrix_view() instead (but then make sure you don’t attempt to destroy the matrix).

1 Like

Thank you so much, now it’s works.