c++ - 将 D 字符串转换为 C 字符*

标签 c++ c d dmd

嗯,基本上这就是我需要的:

  • 我有一个 extern(al) char * 变量
  • 我想给一个D字符串赋值

代码:

import std.stdio;
import std.string;
import core.stdc.stdlib;

extern (C) int yyparse();
extern (C) extern __gshared FILE* yyin;
extern (C) extern __gshared char* yyfilename;

void main(string[] args)
{
    string filename = args[1];

    auto file = File(filename, "r");

    yyfilename = toStringz(filename);
    yyin = file.getFP();

    yyparse();
}

但是,toStringz 函数返回此错误:

main.d(15): Error: cannot implicitly convert expression (toStringz(filename)) of type immutable(char)* to char*

知道出了什么问题吗?

最佳答案

问题在于 yyfilenametoStringz 传递字符串时的返回值具有不同的 const 限定符。 filename 是不可变的(D stringimmutable(char)[] 的别名),但是 yyfilename 不是有任何 const 限定符,因此是可变的。

你有两个选择:

  1. 如果您知道 yyfilename 不会在您的程序的其他地方被修改,您应该将其声明为 const(char)* 而不是 char*.
  2. 否则,您应该在转换时创建 filename 的拷贝:toUTFz!(char*)(filename)

关于c++ - 将 D 字符串转换为 C 字符*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22412898/

相关文章:

将字节复制到结构会给出错误的值

d - 如何在 Vibe.d 中返回带有 HTTP 代码的 JSON?

d - 什么是惯用的(又名 "right")方法将整数集(或至少列表)作为 D 中的模板参数传递?

http - 为获取的文件设置 MIME 类型

c - 数组搜索只需创建一个指针即可

c++ - 将 32 位整数存储到磁盘的绝对最快方法?

c++ - unordered_map 在 VS10 中抛出 bad_alloc 但在 VS9 中没有,这是一个错误吗?

c++ - 使用 opencv 编译代码 -/usr/bin/ld : cannot find -lippicv

C++/CLI -- 访问结构成员

c++ - 指向成员函数错误的指针