简体   繁体   English

将D字符串转换为C char *

[英]Convert D string to C char*

Well, basically that's what I need : 好吧,基本上这就是我需要的:

  • I've got an extern (al) char * variable 我有一个extern (al) char *变量
  • I want to assign the value of a D string 我想分配D字符串的值

Code : 代码:

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();
}

However, the toStringz function returns this error : 但是, toStringz函数返回此错误:

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

Any idea what's going wrong? 知道出了什么问题吗?

You can use: 您可以使用:

import std.utf;

void main()
{
    string filename;
    char* yyfilename;
    yyfilename = toUTFz!(char*)(filename);
    // yyfilename = filename.toUTFz!(char*);  // or with UFCS syntax
}

The problem is that yyfilename , and the return value of toStringz when it is passed a string, have different const qualifiers. 问题是yyfilename和传递字符串时toStringz的返回值具有不同的const限定符。 filename is immutable (D string is an alias to immutable(char)[] ), however yyfilename does not have any const qualifier, and is thus mutable. filename是不可变的(D stringimmutable(char)[]的别名),但是yyfilename没有任何const限定符,因此是可变的。

You have two options: 您有两种选择:

  1. If you know that yyfilename will not bemodified elsewhere in your program, you should declare it as const(char)* instead of char* . 如果您知道yyfilename不会在程序的其他地方修改, yyfilename将其声明为const(char)*而不是char*
  2. Otherwise, you should create a copy of filename when converting it: toUTFz!(char*)(filename) . 否则,您应该在转换时创建filename的副本: toUTFz!(char*)(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM