嗯,基本上这就是我需要的:
- 我有一个
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*
知道出了什么问题吗?
最佳答案
问题在于 yyfilename
和 toStringz
传递字符串时的返回值具有不同的 const 限定符。 filename
是不可变的(D string
是 immutable(char)[]
的别名),但是 yyfilename
不是有任何 const 限定符,因此是可变的。
你有两个选择:
- 如果您知道
yyfilename
不会在您的程序的其他地方被修改,您应该将其声明为const(char)*
而不是char*
. - 否则,您应该在转换时创建
filename
的拷贝:toUTFz!(char*)(filename)
。
关于c++ - 将 D 字符串转换为 C 字符*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22412898/