【问题标题】:D problems with static arrays and C interoperability静态数组和 C 互操作性的 D 问题
【发布时间】:2018-04-12 19:43:12
【问题描述】:

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

【问题讨论】:

  • 为什么要在 C 代码中添加 extern "C"?
  • @AhmedMasud 因为我使用 c++ 编译器。有问题吗?
  • 是的! C++ 不是 C!它们是非常不同的语言,其中一个明显的区别就是您使用的语言。其他的则更微妙。在标记语言之前先学习语言。
  • 好的,但我也在 C++ 端尝试了extern (C++) 没有extern "C"。还将vec3f 转换为一个结构,其中 float[3] 表示为 3 个连续的浮点字段,如 x、y、z,使其工作。
  • 它有所不同,因为链接发生的方式,extern "C" 应该产生一个与 C 兼容的对象,但是不确定你是否正确链接了东西,你可以发布你正在使用的命令行绑定对象?

标签: interop d cross-language


【解决方案1】:

尝试在 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

【讨论】:

    猜你喜欢
    • 2019-04-29
    • 2012-11-03
    • 2013-01-15
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多