-1

I have a background in running simulations in MatLab, and am currently learning C++ to run the simulations whilst still using MatLab to plot through the MatLab engine. The code below shows an example piece of code I have written to generate a variable, pass it to the MatLab workspace, plot it, then pass another variable back to C++.

#include <iostream>
#include "engine.h"
//#include "mex.h"



using namespace std;

void main()
{

    //Create pointer for matlab engine
    Engine *matlab;

    //Open matlab engine interface
    matlab = engOpen("null");

    //Create variable
    double timedata[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    mxArray *T = mxCreateDoubleMatrix(1, 10, mxREAL);
    memcpy((void *)mxGetPr(T), (void *)timedata, 10 * sizeof(double));

    //Put variable into workspace
    engPutVariable(matlab, "workspaceT", T);

    //Evaluate strings in MatLab
    engEvalString(matlab, "D = workspaceT+2;");
    engEvalString(matlab, "plot(workspaceT,D);");

    //Get variable from MatLab workspace
    mxArray *d = engGetVariable(matlab, "D");

    double b[10];
    for (int i = 0; i < 9; i++)
    {
        b[i] = (double)mxGetPr(d)[i];
        cout << b[i];
    }
    cout << endl;

    system("pause");

    //Close matlab engine interface
    engClose(matlab);


}

The part that I am specifically interested in is this...

memcpy((void *)mxGetPr(T), (void *)timedata, 10 * sizeof(double));

I have absolutely no idea what this piece of code is doing. I have had a look at the documentation (http://www.cplusplus.com/reference/cstring/memcpy/) and it hasn't exactly enlightened me. The part that I particularly don't get is the use of (void *). As I stated, my background is in MatLab, so I'm not exactly an expert in C++, so if anyone could explain what is happening here as if I am a five year old, it would be very much appreciated!

Thanks,

Seb.

4

1 回答 1

1

This is prototype of memcpy

void * memcpy ( void * destination, const void * source, size_t num );

First 2 parameters of memcpy are void*. (void*) is explicit (C-style) cast which casts any pointer to pointer to void.

However it's not needed because it can happen implicitly :

int *pointer_to_int;
void *pointer_to_void = (void*)pointer_to_int;//explicit cast

pointer_to_void = pointer_to_int; //implicit cast
于 2016-05-26T08:22:52.793 回答