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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现