【问题标题】:Loading Classes From Static Library in D从 D 中的静态库加载类
【发布时间】:2016-04-16 04:50:36
【问题描述】:

我从这个答案中阅读了如何从静态库中加载函数:https://stackoverflow.com/a/10366323/6123767

但是我需要从静态库中加载一个类,而不仅仅是一个函数,我该如何实现呢?

【问题讨论】:

    标签: class static-libraries d static-linking


    【解决方案1】:

    类在导出的二进制文件中实际上不是一个东西。它们基本上只是一个花哨的结构。结构基本上只是带有数据的内存布局。库大多只包含函数。

    所以你真正想做的是创建一个包含成员函数声明的类,并在其中添加成员变量,如下所示:

    库/somelib.d:

    module somelib;
    
    class Foo
    {
        private long member;
    
        this(long n)
        {
            member = n * 2;
        }
    
        int func(int x)
        {
            return cast(int) (x + member);
        }
    }
    

    包装器/somelib.d:

    module somelib; // module names need to match!
    
    class Foo
    {
        private long member;
        this(long n);
        int func(int x);
    }
    

    app.d:

    module app;
    import std.stdio;
    import somelib;
    
    void main()
    {
        Foo foo = new Foo(4);
        writeln("foo: ", foo);
        writeln("func: ", foo.func(5));
    }
    

    使用dmd -lib library/somelib.d -ofsomelib.a(或Windows 上的.lib)编译库

    使用dmd app.d -Iwrapper somelib.a -ofapp(或Windows 上的.lib/.exe)编译可执行文件

    我做了-Iwrapper 而不是指定文件名,因此模块名称可以匹配文件/文件夹路径,因为 wrapper/somelib.d 的模块名称 必须 匹配 library/somelib 的模块名称.d 因为这就是函数名称在 D 中的错位方式。

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多