Boost logo

Ublas :

Subject: [ublas] Help with raw pointers and matrix/vector interoperability with other libraries through casts
From: Jesse Perla (jesseperla_at_[hidden])
Date: 2008-09-13 15:32:29

As I am using a variety of libraries for my projects, and while I will
standardize on using ublas::matrix and ublas::vector, the other libraries
use a variety of C-style array/matrix, stl::vector, and homegrown
libraries. I am looking for a relatively straightforward way to pass in my
ublas vectors/matricies to these functions without copying all of the
values, etc. For now, I can focus on dense column:major only, with
assumption of no reallocation/resizing.

I have seen some discussion about getting the raw pointer to the
matrix/vector libraries, but I am having trouble getting it to work. Also
have heard about adaptors, but don't quite understand what people are
talking about.

It key cases are:
1) std::vector
The faq suggests using a copy iterator to go between them, but I don't want
to copy the data. std::vector does support initialization from a data
pointer... I would love something like:

ublas::vector<double> v(4);
std::vector<double>& v_std = ublas_to_std_vector<double>(v);
//Or better yet, if I could define a cast for this?

2) C-style array and matrix:
a) Want to be able to pass in the matrix or vector to C style functions:
   //Couldn't get matrix type operators to work. I tried to various
permutations on:
    ublas::matrix<int> A2(2,2);
    int** Ap2;
    Ap2 = &([0]);
    Ap2[0][0] = 1;
   //It appears that for matrices, the data() returns back an int* instead
of an int** which is what most functions require. Perhaps there is an
unsafe cast that would solve this problem? I can't figure out how to trick
C style int** matrices to think they are of size NxN from a raw pointer
without allocating data to determine pointer offsets.

   //The following seemed to work for ublas::vector though.
    ublas::vector<int> A(2);
    int* Ap;
    Ap = &([0]);
    Ap[0] = 1;

b) If C style functions return data, would like to put the ublas wrapper
around them. I assume this is done with calling a constructor on
ublas::matrix or ublas::vector with the pointer.

3) Home Grown matrix libraries:
A million exist, and nearly all seem to have constructors for passing in a
pointer to data, so I think the problem
Maybe a cast/function could be written to do this generically since the
concept of a copy constructor with pointers may be all that is needed from
the library? But I don't know enough about generic programming/casts to
write this myself. Is the best way to deal with this stuff to define a
reinterpret_cast? If so, any good examples of how to do so and how to add
these to libraries without modifying the underlying boost::ublas, etc.?

Any ideas or example code for this kind of stuff?

Thanks for your help,