簡體   English   中英

將D字符串轉換為C char *

[英]Convert D string to C char*

好吧,基本上這就是我需要的:

  • 我有一個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*

知道出了什么問題嗎?

您可以使用:

import std.utf;

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

問題是yyfilename和傳遞字符串時toStringz的返回值具有不同的const限定符。 filename是不可變的(D stringimmutable(char)[]的別名),但是yyfilename沒有任何const限定符,因此是可變的。

您有兩種選擇:

  1. 如果您知道yyfilename不會在程序的其他地方修改, yyfilename將其聲明為const(char)*而不是char*
  2. 否則,您應該在轉換時創建filename的副本: toUTFz!(char*)(filename)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM