简体   繁体   English

从C-DLL函数读取MATLAB中的int和字符串数组

[英]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: 我正在尝试在MATLAB中读取以下函数的int和字符串数组:

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

In CI just do the following code and it works: 在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);

In MATLAB I'm trying the following code with no luck: 在MATLAB中,我很幸运地尝试以下代码:

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". 我已经尝试初始化libpointers,并且得到了相同的消息“检测到细分违规”。 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. 您绝对需要初始化您的指针-现在它们指向无处,它们被初始化为0。这很可能导致段错误。 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: 您也可以传递普通的matlab数组,而不用创建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 . 您可以在此处找到有关matlab类型和相应本机类型的信息

Edit Here is a simple shared library function that takes your input (your comments below) and prints one string on the screen using mexPrintf “编辑 ”是一个简单的共享库函数,可接收您的输入(下面的注释)并使用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]]). 该函数使用整数数组(在您的情况下为index [0])中的第一个值从字符串数组(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. 如果您可以正确执行上述操作,则很可能您提供给getdata的数据是错误的,并且您必须在该处出现段错误。 Maybe you modify the input parameters in some way? 也许您以某种方式修改了输入参数? eg create non-NULL terminated strings? 例如创建非NULL终止的字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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