我正在尝试使用 mexCallMATLAB()
读取图像。以下是代码:
#include "mex.h"
#include <matrix.h>
#include <string.h>
#include <stdio.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxChar *string, *img;
int dims[2] = {1, 100};
char *str = "D:\\Acads\\NUS\\CBIS\\TEST\\SampleImages\\set1139R0stack1000Color0St0.tiff.tif"; // Path of the image file
string = mxCreateCharArray(2, (const int *)dims);
memcpy(mxGetPr(string), str, sizeof(char) * (strlen(str) + 1));
mexCallMATLAB(1, img, 1, &string, "imread");
}
代码编译没有错误,但在执行时抛出以下错误消息:
??? Error using ==> imread at 315
File "%^&*$#@! (Some special character string)" does not exist.
当我打印变量 string
的值时,我得到了正确的路径,但我不明白调用 MATLAB 函数时发生了什么。
最佳答案
在 Matlab MEX 中,字符串的行为因版本而异。
在当前版本中,我认为字符串表示为 16 位字符串 (UNICODE) 而不是 ASCII。字符数组的大小必须与不包含终止 NUL 的字符串的长度一样长(这适用于所有 MATLAB 版本)。
为避免出现问题,您应该使用特殊的 C-string-to-mxArray 函数(我认为它被命名为 mxCreateString 左右)。
顺便说一句:“string”和“img”是“mxArray *”类型,而不是“mxChar *”类型。
mexCallMATLAB 的第二个参数必须是指向“img”的指针,而不是“img”本身!
关于从 MEX 调用 MATLAB 函数 "imread",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18567077/