translate alias align from C to D
Matheus Catarino
matheus-catarino at hotmail.com
Mon Jan 13 14:52:05 UTC 2025
On Monday, 13 January 2025 at 11:36:45 UTC, Dakota wrote:
> I want tranlate this into d without importC, what is the best
> way to do it?
You could simply use dstep or dmd/ldc2 `-H`|`-Hf=<filename>`.
My test on linux shows that both can translate/convert the file.
Although there are differences such as:
#### dstep:
- copies the comments
- does not found `<stdalign.h>`
- does not translate ifdef/endif to version
- translates C source and C headers
#### dmd/ldc2 importC:
- does not copy comments
- does not translate ifdef/endif to version
- translate only C source files [add header in source]
- also translates compiler directives
#### Both translation
**from**
```c
typedef CGLM_ALIGN_IF(16) float vec4[4];
typedef CGLM_ALIGN_IF(16) float vec2[2];
typedef CGLM_ALIGN_IF(16) vec2 mat2[2];
typedef CGLM_ALIGN_MAT vec4 mat4[4];
```
**to**
```d
alias vec4 = float[4];
alias vec2 = float[2];
alias mat2 = float[2][2];
alias mat4 = float[4][4];
```
However, `CGLM_ALIGN`:
**from**
```c
#if defined(_MSC_VER)
/* do not use alignment for older visual studio versions */
# if _MSC_VER < 1913 /* Visual Studio 2017 version 15.6 */
# define CGLM_ALL_UNALIGNED
# define CGLM_ALIGN(X) /* no alignment */
# else
# define CGLM_ALIGN(X) __declspec(align(X))
# endif
#else
# define CGLM_ALIGN(X) __attribute((aligned(X)))
#endif
#ifndef CGLM_ALL_UNALIGNED
# define CGLM_ALIGN_IF(X) CGLM_ALIGN(X)
#else
# define CGLM_ALIGN_IF(X) /* no alignment */
#endif
#ifdef __AVX__
# define CGLM_ALIGN_MAT CGLM_ALIGN(32)
#else
# define CGLM_ALIGN_MAT CGLM_ALIGN(16)
#endif
```
**to**
```d
// importC
auto CGLM_ALIGN(__MP19)(__MP19 X)
{
return __attribute(aligned(X));
}
auto CGLM_ALIGN_IF(__MP20)(__MP20 X)
{
return CGLM_ALIGN(X);
}
```
```d
// dstep
/* do not use alignment for older visual studio versions */
/* Visual Studio 2017 version 15.6 */
/* no alignment */
alias CGLM_ALIGN_IF = CGLM_ALIGN;
/* no alignment */
enum CGLM_ALIGN_MAT = CGLM_ALIGN(16);
```
In any case, it will require manual adjustments.
**Note:** This isn't perfect, but hopefully it gives you some
idea of what it would be like.
```d
import core.stdcpp.xutility;
version (CppRuntime_Microsoft)
{
static if (_MSC_VER < 1913)
{
enum CGLM_ALL_UNALIGNED = true;
}
else
{
enum CGLM_ALIGN(ushort X) = "align(" ~ X.stringof ~ ")";
}
}
else
{
enum CGLM_ALIGN(ushort X) = "align(" ~ X.stringof ~ ")";
}
static if (!is(typeof(CGLM_ALL_UNALIGNED)))
{
enum CGLM_ALIGN_IF(ushort X) = CGLM_ALIGN!X;
}
version (AVX)
{
enum CGLM_ALIGN_MAT = CGLM_ALIGN!32;
}
else
{
enum CGLM_ALIGN_MAT = CGLM_ALIGN!16;
}
```
More information about the Digitalmars-d-learn
mailing list