[英]Convert D string to C char*
好吧,基本上這就是我需要的:
extern
(al) char *
變量 代碼:
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 string
是immutable(char)[]
的別名),但是yyfilename
沒有任何const限定符,因此是可變的。
您有兩種選擇:
yyfilename
不會在程序的其他地方修改, yyfilename
將其聲明為const(char)*
而不是char*
。 filename
的副本: toUTFz!(char*)(filename)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.