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;
}
posted @   zjh6  阅读(20)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示