静态阵列和 C 互操作性的 D 问题



我在将包含静态数组的 D 结构传递给 C 时遇到问题。

D 代码:

extern (C){
    struct vec3f{
        float[3] array;
    }
    void testVec3f(vec3f v);
}
...
void test(){
    float[3] ar = [1f,2f,3f];
    vec3f v = vec3f(ar);
    testVec3f(v);
}

C 代码:

extern "C" struct vec3f{
    float array[3];
};
extern "C" void testVec3f(vec3f a){
    printf("x=%f, y=%f, z=%fn", a.array[0], a.array[1], a.array[2]);
}

结果:x=0.000000, y=0.000000, z=0.000000。 我还检查了 D 和 C 中的两个结构是否具有相同的大小 - 12 字节。

尝试在

C 和 D 之间按值传递结构时会遇到一大堆麻烦;特别是如果你的 D 编译器在后端使用 GNU 编译器,而你可能在项目的某些部分使用 clang++。

gnu c++ 和 clang++ 处理对象传递的方式不同,extern "C" 增加了另一层复杂性。 您最好避免所有这些,并通过引用传递您的值:

下面是使用 clang-c++ 和 dmd 的示例(正常工作(:

测试.d:

import std.stdio;
struct vec3f {
    float [3] array;
}
extern (C) {
    void print_vec3f(vec3f *v);
}
void main()
{
    vec3f v = vec3f([1f, 2f, 3f]);
    print_vec3f(&v);
}

vect3.cc:

#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif 
struct vec3f {
        float array[3];
};
void print_vec3f(struct vec3f *v)
{
    printf("x: %f, y: %f, z: %fn", v->array[0], v->array[1], v->array[2]);
}
#ifdef __cplusplus
};
#endif

编译使用:

clang++ -o vect3.o -c vect3.cc
dmd   test.d vect3.o
./test
x: 1.000000, y: 2.000000, z: 3.000000

最新更新