[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Octave equivalent to A = mxGetPr(prhs[0]);

From: John W. Eaton
Subject: Re: Octave equivalent to A = mxGetPr(prhs[0]);
Date: Fri, 9 Jun 2006 09:25:33 -0400

On  9-Jun-2006, Fredrik Lingvall wrote:

| David Bateman wrote:
| >
| >>  const Matrix tmp = args(0).matrix_value();
| >>   //A_M = mxGetM(prhs[0]);
| >>   A_M = tmp.rows();
| >>   //A_N = mxGetN(prhs[0]);
| >>   A_N = tmp.cols();
| >>   //A = mxGetPr(prhs[0]);
| >>   A = (double*) tmp.fortran_vec();
| >>
| >> Solved my problem.
| >>     
| >
| > Yes, but the last line probably made a copy of the data with this last
| > line with the cast to (double *)!!

No, I don't think casting a pointer can't cause the pointed-to data to
be copied.  It just tells the compiler to "ignore that const qualifier
and let me do things I'm not supposed to be doing". 

| > see what value rep->count has... If it is "1" you've made a copy..

If that were going to happen, it would have been done at the point of
the call to fortran_vec.  But since you are calling fortran_vec on a
const object, it doesn't copy, it just calls the data method, which
never copies and always returns pointer to const.  See the code in
liboctave/Array.{h,cc} for the const and non-const versions of the
fortran_vec method.

| I did  a A[0] = 0.0; and the 1st element of the input parameter was 
| changed to 0 after I
| called my oct-file so I think that it worked. But anyway, how do you 
| suggest that I should
| write the code?

You can't do it in a legitimate way with Octave (or Matlab, as far as
I know).

The fortran_vec method forces a copy.  The cast just allows you to
sneak something past the compiler.  The data is really supposed to be
const in order to preserve the semantics of the scripting language.
BTW, since this is C++, you should probably be using
const_cast<double*> (X) to make it clear to readers of your code that
you are casting away const.

Your code may also have some unwanted side effects.  If someone using
your functions writes

  A = generate_large_matrix ();
  B = A;                            ## no actual copy of data here.
  your_function (A);

then both A and B will change.  This may surprise some users, since
this is not the way Octave (or Matlab) is supposed to work.  You
might argue that this sort of behavior should be possible, but it is
not part of the "Matlab" language (yet, that I know of).


reply via email to

[Prev in Thread] Current Thread [Next in Thread]