d不能赋值外C指针至D变量
原文
参考1
参考2
(extern(C)函数指针不能赋给D变量)?还是要注解函数?如果是,怎么做?
问题是ScopeCleanup构不能通过传递从C导入的函数指针来构造.
需要创建包含回调类型的别名:
alias DCallback = extern(C) void function();
DCallback cb;
cb = yourCFunction;
可以这样:
import core.stdc.stdio: puts;
auto p1 = &puts;
extern (C) int function(const char* s) p2 = &puts;
如果试图把'extern(C)'函数指针赋值给'extern(D)'函数指针(默认值),这不行.编译器会用D的调用约定发出代码,但被调函数将假定C的调用约定.
alias CFunction = extern(C) void function();
/// RAII,析构时,调用构造器传过来的函数.
struct ScopeCleanup
{
@disable this();
this(CFunction cleanup) { this.cleanup = cleanup; }
~this() { cleanup(); }
CFunction cleanup;
}
导入函数不仅是extern(C),而且还有nothrow@nogc.很公平,我把它添加到别名中.但仍然不行,因为,按如下绑定:
extern(C) void function() nothrow @nogc*
*为函数指针的指针.所以,要这样:
alias CFunctionPtr = extern(C) void function() nothrow @nogc*;
struct ScopeCleanup
{
@disable this();
this(CFunctionPtr cleanup) { this.cleanup = cleanup; }
~this() { (*cleanup)(); }//先用*,再调用.
CFunctionPtr cleanup;
}
浙公网安备 33010602011771号