1

我在将包含静态数组的 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 个字节。

4

1 回答 1

2

尝试在 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: %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
于 2018-04-12T20:41:24.577 回答