필터 지우기
필터 지우기

mex C struct pointer

조회 수: 3 (최근 30일)
俊凯 王
俊凯 王 2021년 9월 8일
답변: 俊凯 王 2021년 9월 8일
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?

채택된 답변

俊凯 王
俊凯 王 2021년 9월 8일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by