D静态数组和C互操作性的问题

时间:2018-04-12 19:43:13

标签: interop d cross-language

我在将包含静态数组的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=%f\n", a.array[0], a.array[1], a.array[2]);

}

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

1 个答案:

答案 0 :(得分:2)

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

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

使用clang-c ++和dmd:

这里的示例(正常工作)

test.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: %f\n", 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