c与matlab兼容,为Matlab编译C MEX文件时size_t和mwSize之间的差异

我目前正在将32位Matlab的一些C MEX文件移植到64位Matlab。

在这样做的时候,我遇到了两种类型,一种是来自Matlab的人,另一种是C标准的。

这就是Matlab文档关于mwSize的说法:

mwSize (C and Fortran)

Type for size values

Description

mwSize is a type that represents size values, such as array dimensions. Use this function for cross-platform flexibility. By default, mwSize is equivalent to int in C. When using the mex -largeArrayDims switch, mwSize is equivalent to size_t in C. In Fortran, mwSize is similarly equivalent to INTEGER*4 or INTEGER*8, based on platform and compilation flags.

维基百科对size_t的评价是这样的:

size_t is an unsigned data type defined by several C/C++ standards (e.g., the C99 ISO/IEC 9899 standard) that is defined in stddef.h.[1] It can be further imported by inclusion of stdlib.h as this file internally sub includes stddef.h[2].

This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of this type or have the return type of size_t. Further, the most frequently used compiler-based operator sizeof should evaluate to a value that is compatible with size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors,[3][4] when moving from 32 to 64-bit architecture, for example.

据我所知,这些类型实际上是相同的。 我的问题是:

是吗

如果是这样,那么哪个将被认为更适合使用编程? 理想情况下,我们希望我们的代码也与未来的Matlab版本兼容。 我猜答案是mwSize,但是我不

编辑:我应该补充一点,Matlab的人正在同时使用这两种方法。 例如:

size_t mxGetN(const mxArray *pm);

是用于检索mxArray的列数的函数。 但是,当人们创建矩阵时,就会使用,

mxArray *mxCreateDoubleMatrix(mwSize m, mwSize n, mxComplexity ComplexFlag);

输入显然应该是mwSize。

嗯...作为基本检查,只需确保它们具有相同的大小:assert(sizeof (size_t) == sizeof (mwSize));并使用其中任何一个即可。 如果assert失败,那么您注定要失败。

@pmg:如果在编译mex函数时不使用-largeArrayDims开关,则断言在size_t大于int的平台上将失败。 这就是拥有mwSize typedef的全部要点。

+1并感谢@Praetorian。 正如我在评论中所说,assert只是一个基本的检查:我不知道混合特定的东西。

定义mwSize是为了向后兼容和可移植性。 如文档所述,当在编译过程中不使用-largeArrayDims开关时,它映射为int;当是size_t时,它映射为size_t。 因此,在第一种情况下,mwSize被签名,但在第二种情况下,没有签名。

在代码中使用mwSize允许您在所有平台上重复使用代码,而不管是否使用该标志。

至于您指出的API不一致,它们是真正的不一致,但不是主要问题。 mxGetN()永远不会返回负数,因此让它返回size_t是可以的。 但是,(我猜测)某些平台上的较早版本或mex API版本期望将int传递给mxCreateDoubleMatrix(),因此将函数定义为采用类型为mwSize的输入使其可移植和/或向后兼容。

简短的答案是,使用mwSize并使用-largeArrayDims编译mex函数。

关于样式的另一个问题:mwIndex和mwSize(在文档中)相同,除了一个用于索引,一个用于大小。 这是什么原因呢? 只是为了使代码更清晰? 因此,在for(i=0; i<=n; i++)中,我将是mwIndex,而n将是mwSize,但对我来说,除法似乎是不必要的。

@Har:我也从未理解拥有mwIndex的原因。 在某些情况下,它的确使代码更易于遵循,但是正如您所指出的那样,当迭代mxArray的某个维度时,与mwSize相比,最终得到的是mwIndex,我也不喜欢。 我倾向于将mwSize用于所有内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值