![](/img/trans.png)
[英]Passing pointer argument in MATLAB to a C-DLL function foo(char**)
[英]Reading int and strings arrays in MATLAB from a C-DLL function
我正在嘗試在MATLAB中讀取以下函數的int和字符串數組:
int DLLEXPORT getdata(int *index, char *id[])
在CI中,只需執行以下代碼即可使用:
int count;
int *index = calloc(MAXLINE, sizeof(int));
char **id = calloc(MAXLINE, sizeof(char*));
for (for i = 0; i < MAXLINE; ++i)
id[i] = malloc(MAXID);
errcode = getdata(index, id);
在MATLAB中,我很幸運地嘗試以下代碼:
errorcode = libpointer('int32');
index = libpointer('int32Ptr');
id = libpointer('stringPtrPtr');
[errorcode, index, id] = calllib('mylib','getdata', index, id);
我已經嘗試初始化libpointers,並且得到了相同的消息“檢測到細分違規”。 有人可以幫我嗎?
您絕對需要初始化您的指針-現在它們指向無處,它們被初始化為0。這很可能導致段錯誤。 如果嘗試初始化它們,則必須做錯了。 嘗試某事。 像這樣
index = libpointer('int32Ptr', [1 2 3 4]);
id = libpointer('stringPtrPtr', {'asdfasdf', 'asdfasdf'});
您也可以傳遞普通的matlab數組,而不用創建libpointer:
[errorcode, index, id] = calllib('mylib','getdata', [1 2 3 4], {'asdfasdf', 'asdfasdf'});
您可以在此處找到有關matlab類型和相應本機類型的信息 。
“編輯 ”是一個簡單的共享庫函數,可接收您的輸入(下面的注釋)並使用mexPrintf在屏幕上打印一個字符串
#include <string.h>
#include <mex.h>
void testfun(int *index, char* id[]){
int idx0 = index[0];
mexPrintf("printing string %d: id[0] %s\n", idx0, id[idx0]);
}
該函數使用整數數組(在您的情況下為index [0])中的第一個值從字符串數組(id [index [0]])中打印指定的字符串。 輸出是
printing string 0: id[0] 01234567890123456789012345678901
因此,請嘗試一下。 請記住,您還必須提供相應的頭文件來加載庫!
如果您可以正確執行上述操作,則很可能您提供給getdata的數據是錯誤的,並且您必須在該處出現段錯誤。 也許您以某種方式修改了輸入參數? 例如創建非NULL終止的字符串?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.