从 MEX 调用 MATLAB 函数 "imread"

标签 c matlab mex

我正在尝试使用 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/

相关文章:

c - flock() 不会阻止其他进程获得独占锁

c - 嵌入式系统编程的松耦合模式

c - 无法运行已编译的C+Gtk+-3软件

Makefile 中的 Cflags 用法

c++ - 从数组到TypedArray <std::complex <double >>的无限制转换?

c++ - 如何在多线程 MEX 函数中打印到控制台?

c++ - Matlab 与外部应用程序(C++)之间的通信

matlab - matlab 中的 for 或 while 循环

Matlab EVAL——将访问范围限制为选定的内置函数/变量子集?

c++ - 在调试 C++ 程序期间调用 round() 函数时,GDB 打印任意值