フィルターのクリア

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 Center および File ExchangeWrite 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