作者vulmoon (百鬼月夜)
看板MATLAB
標題[問題] c structure轉matlab疑問
時間Wed Dec 19 22:12:29 2012
各位大大好!
我目前在寫C轉matlab的程式
也就是要用mex去編譯.c檔
但是現在碰到一個關於structure的傳遞問題
目前我的構想是透過matlab初始一個structure
然後再將這個structure輸出(return)
等等把C code貼在最下方
先說我目前碰到的問題
現在我已經可以把創起來的struct初始成功
輸出裡面的資料要確認也都OK
但是就在她要把這個struct傳出來(return)的時候
出錯了!!!!
而且這個錯誤是會crash掉matlab的
已經搞好久了
還是無解~
原本以為是沒有把初始好的struct回存到plhs[0]
所以使用mxSetData把pointer回存回去
但好像還是不行
所以希望版上有經驗的大大可以幫幫我
幫我找出問題點在哪邊
可以順利輸出~拜託拜託!
感恩
---------- 以下是程式碼 ----------
#include "mex.h"
#define Uint8 unsigned char
#define Int8 char
#define Uint16 unsigned short
#define Int16 short
#define Uint32 unsigned int
#define Int32 int
#define NUMBER_OF_STRUCTS (sizeof(*img)/sizeof(ImgInfo))
#define NUMBER_OF_FIELDS (sizeof(field_names)/sizeof(*field_names))
typedef struct
{
Uint8 depth;
Uint16 imgWidth;
Uint16 imgHeight;
Uint16 *imgData;
}ImgInfo;
void Init(ImgInfo *img)
{
img->depth = 2;
img->imgWidth = 256;
img->imgHeight = 256;
img->imgData = (Uint16*)malloc(sizeof(ImgInfo));
memset(img->imgData, 0, sizeof(Uint16)*img->imgWidth*img->imgHeight);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const char *field_names[] = {"depth", "imgWidth", "imgHeight", "imgData"};
ImgInfo *img;
mwSize dims[2] = {1, NUMBER_OF_STRUCTS};
plhs[0] = mxCreateStructArray(2, dims, NUMBER_OF_FIELDS, field_names);
img = mxGetPr(plhs[0]);
Init(img);
printf("%d\n", img->depth);
printf("%d\n", img->imgWidth);
printf("%d\n", img->imgHeight);
mxSetData(plhs[0], img);
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.25.174.108
※ 編輯: vulmoon 來自: 114.25.174.108 (12/19 22:33)
1F:推 sunev:mxGetPr 得到的東西的型別是ImgInfo*嗎? 12/19 23:00
2F:→ vulmoon:我其實不是很確定,它是說取實數,可是我用它可以寫值進去 12/19 23:05
3F:推 sunev:可以是什麼意思,你不是說matlab crash了嗎? 12/20 00:58
4F:→ vulmoon:我有三行printf把值print出來看,有print成功,可是當要 12/20 07:24
5F:→ vulmoon:結束這函式時,它要輸出這結構就會crash。 12/20 07:25
6F:推 sunev:你的crash指的是matlab被強迫結束嗎? 12/20 14:55
7F:→ sunev:要結束這函式是指這個mex file執行結束了嗎?然後你在matlab 12/20 14:55
8F:→ sunev:打這個變數,想看裡面的內容時,matlab crash了? 12/20 14:56
9F:→ vulmoon:沒錯!是matlab被強制結束!它會跳出幾個選項給你選,但在你 12/20 19:00
10F:→ vulmoon:重開matlab之前都無法下指令。結束這函式的確是只該mex fi 12/20 19:01
11F:→ vulmoon:-le執行結束。一執行結束就crash,還無法打這個變數。 12/20 19:05
12F:推 sunev:這不叫結束函式,這叫編譯成功。 12/21 02:31
13F:→ sunev:話說回來,如果matlab被強制結束,你怎麼知道printf有成功? 12/21 02:32
14F:→ vulmoon:噢噢~可能我表達錯誤!我編譯都是成功的!是執行函式的時候 12/21 19:04
15F:→ vulmoon:才crash!所以才會pringf成功! 12/21 19:04
16F:推 sunev:編譯成功不代表printf成功耶,也不代表mxSetData成功 12/22 03:14
17F:→ sunev:也不代表輸出結構成功。 12/22 03:14
18F:→ vulmoon:當然是有看到printf資料我才知道printf有成功阿@@!也就是 12/22 07:34
19F:→ vulmoon:輸出結構時失敗才會crash!!mxSetData有沒有成功不確定!因 12/22 07:35
20F:→ vulmoon:為無法輸出結構,所以我不知道有沒有Set成功! 12/22 07:35
21F:推 sunev:所以你的意思是在crash之前,你有看過matlab的command 12/22 16:57
22F:→ sunev:windows 印出訊息? 12/22 16:57
23F:→ vulmoon:是的~沒有錯!我昨天有更改過程式~是可以輸出結構了~不過方 12/23 12:17
24F:→ vulmoon:法很爛!我晚點PO上來!再請你幫我看一下! 12/23 12:17