[英]Convert D string to C char*
Well, basically that's what I need : 好吧,基本上这就是我需要的:
extern
(al) char *
variable extern
(al) char *
变量 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 string
是immutable(char)[]
的别名),但是yyfilename
没有任何const限定符,因此是可变的。
You have two options: 您有两种选择:
yyfilename
will not bemodified elsewhere in your program, you should declare it as const(char)*
instead of char*
. yyfilename
不会在程序的其他地方修改, yyfilename
将其声明为const(char)*
而不是char*
。 filename
when converting it: toUTFz!(char*)(filename)
. filename
的副本: toUTFz!(char*)(filename)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.