另一种方法是基于D的系统类的层次上:
所有对象继承或明或暗地在对象。
这样的想法是PIMPL实现在OuterClass,生成相应的 二档,手动从二档 删除OuterClassPrivate的所有定义和改变平普尔成员的声明。
例如:
共享库的第一版本
module pimpl.mylib;
class PimplTest
{
this()
{
mImpl = new PimplTestPrivate();
}
~this()
{
}
string sayWhat(string what)
{
return mImpl.ku ~ " " ~ what;
}
private class PimplTestPrivate
{
string ku = "Ku!!1";
}
private PimplTestPrivate mImpl;
}
测试应用:
module main;
import std.stdio;
import pimpl.mylib;
void main()
{
PimplTest t = new PimplTest();
writeln(t.sayWhat("?"));
}
共用MYLIB可以内置下面的方式(在Linux下):
$ dmd -H -c mylib.d -fPIC
$ dmd -ofmylib.so mylib.o -shared -defaultlib=libphobos2.so -L-rpath=/path/to/where/shared/phobos/library/is
然后编辑genereated二档:
// D import file generated from 'mylib.d'
module pimpl.mylib;
class PimplTest
{
this();
~this();
string sayWhat(string what);
// NOTE this
private Object mImpl;
}
编译测试itsel
$ dmd -c main.d /path/to/first/version/of/mylib.di
$ ln -s /path/to/first/version/of/mylib.so .
$ dmd main.o -L-l:mylib.so -defaultlib=libphobos2.so -L-rpath=/path/to/where/shared/phobos/library/is:.
$ ./main
Say: ?
然后我们改变MYLIB:
module pimpl.mylib;
import std.conv;
class PimplTest
{
this()
{
mImpl = new PimplTestPrivate();
}
~this()
{
}
string sayWhat(string what)
{
return mImpl.getMessage1(mImpl.getValue(), what);
}
private class PimplTestPrivate
{
int getValue()
{
return 42;
}
string ku = "Ku!!1";
string getMessage1(int x, string y)
{
return "x = " ~ to!(string)(x) ~ ", " ~ y;
}
double pi = 22.0/7.0;
}
private PimplTestPrivate mImpl;
}
编译并替换二进制共享对象(所以文件)的第一个版本的mylib刚建成一个。运行测试应用程序不能崩溃,但输出会有所不同。
这将是链接器的责任,以验证内存布局的假设,因为这是唯一知道所有这些 –
我认为这是不正确的。数据结构不存储到目标文件。链接器不知道类型。 –
但编译器不需要知道'.d'和'.di'文件 –