简体   繁体   中英

Reading int and strings arrays in MATLAB from a C-DLL function

I'm trying to read int and strings arrays in MATLAB of the following function:

int DLLEXPORT getdata(int *index, char *id[])

In CI just do the following code and it works:

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);

In MATLAB I'm trying the following code with no luck:

errorcode = libpointer('int32');
index = libpointer('int32Ptr');
id = libpointer('stringPtrPtr');

[errorcode, index, id] = calllib('mylib','getdata', index, id);

I've already tried to initialize the libpointers and I got the same message "Segmentation violation detected". Someone could help me?

You definitely need to initialize your pointers - right now they point to nowhere, they are initialized to 0. This most likely causes the segfault. If you have tried to initialize them, you must have done it wrong. Try sth. like this

index = libpointer('int32Ptr', [1 2 3 4]);
id = libpointer('stringPtrPtr', {'asdfasdf', 'asdfasdf'});

You can also pass normal matlab arrays instead of making a libpointer:

[errorcode, index, id] = calllib('mylib','getdata', [1 2 3 4], {'asdfasdf', 'asdfasdf'});

You can find information about matlab types and the corresponding native types here .

Edit Here is a simple shared library function that takes your input (your comments below) and prints one string on the screen using 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]);
}

The function uses the first value from integer array (index[0] in your case) to print the specified string from an array of strings (id[index[0]]). The output is

printing string 0: id[0] 01234567890123456789012345678901

So it works, try it. Remember you must also provide the corresponding header file to loadlibrary!

If you can execute the above correctly, most likely the data you supply to getdata is wrong and you must be getting a segfault somewhere there. Maybe you modify the input parameters in some way? eg create non-NULL terminated strings?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM