Filter löschen
Filter löschen

mex C struct pointer

3 Ansichten (letzte 30 Tage)
俊凯 王
俊凯 王 am 8 Sep. 2021
Beantwortet: 俊凯 王 am 8 Sep. 2021
how can i use mex function return a structer pointer to matlab?is there any possbile for mex function return a pointer?as i know mexfunction just can return a double *
like this is a structer in C,can i return a pointer which point to this structer in mex function?

Akzeptierte Antwort

俊凯 王
俊凯 王 am 8 Sep. 2021
use intptr_t ,i got it
code like this
pointer_return.cpp
#include "mex.h"
#include "matrix.h"
struct test
{
struct test* left;
struct test* right;
int id;
};
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[]){
struct test* root = (test*)malloc(sizeof(test));
struct test* root_left = (test*)malloc(sizeof(test));
struct test* root_right = (test*)malloc(sizeof(test));
root_right->left = nullptr;//这个必须赋值为空值指针,不赋值的话访问不了
root_right->right = nullptr;
root_left->right = nullptr;
root_left->left = nullptr;
root->id = 0; root_left->id = 1; root_right->id = 2;
root->left = root_left;
root->right = root_right;
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
double* pointer_to_tree = mxGetPr(plhs[0]);
pointer_to_tree[0] = (intptr_t) root;
}
change_intopointer.cpp
#include "mex.h"
#include "matrix.h"
struct test
{
struct test* left;
struct test* right;
int id;
};
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[]){
double* root_double = mxGetPr(prhs[0]);
intptr_t pointer1 = (intptr_t) root_double[0];
struct test *test_root = (struct test*) pointer1;
mexPrintf("root id is %d\n",test_root->id);
mexPrintf("left id is %d\n",test_root->left->id);
mexPrintf("right id is %d\n",test_root->right->id);
}
matlab.m
tic
root=pointer_return();
toc
tic
change_intopointer(root)
toc

Weitere Antworten (0)

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by