Generating C# code for a given .proto file produces an error while opening a file
I use google::protobuf::compiler::csharp::Generator to generate .cs file.
First, I create google::protobuf::compiler::Importer. To do so, I need to get an instance of DiskSourceTree and implement MultiFileErrorCollector:
class ErrorCollector : public MultiFileErrorCollector
{
public:
void AddError(const std::string& filename, int line, int column, const std::string& message) override
{
std::fstream stream;
stream.open(filename);
stream << message;
stream.close();
}
void AddWarning(const std::string& filename, int line, int column, const std::string& message) override
{
std::fstream stream;
stream.open(filename);
stream << message;
stream.close();
}
};
After that, I implement GeneratorContext to pass it to Generator::Generate():
class Context : public GeneratorContext
{
public:
google::protobuf::io::ZeroCopyOutputStream* Open(const std::string& filename)
{
stream_ptr = std::make_unique<std::fstream>();
stream_ptr->open(filename);
proto_stream = std::make_unique<google::protobuf::io::OstreamOutputStream>(stream_ptr.get());
return proto_stream.get();
}
private:
std::unique_ptr<std::fstream> stream_ptr;
std::unique_ptr<google::protobuf::io::OstreamOutputStream> proto_stream;
};
The error occurs at the stage of importing .proto-file. The debugger says, const google::protobuf::FileDescriptor* desc = importer->Import(FILENAME); results to null.
It's probably something with the file path or even with my understanding of how it all works. I would appreciate any help.
Here's my main function:
int main()
{
// building an Importer
DiskSourceTree* tree = new DiskSourceTree;
ErrorCollector* collector = new ErrorCollector;
Importer* importer = new Importer(tree, collector);
const std::string FILENAME = "C:/my/path/my_file.proto";
const google::protobuf::FileDescriptor* desc = importer->Import(FILENAME); // the error is here
// generating the code
Generator generator;
Context* context = new Context();
std::string* error_str = new std::string;
error_str->reserve(256);
if (generator.Generate(desc, "", context, error_str)) // this line produces an exception since the descriptor is invalid
{
std::cout << "success!";
}
delete tree;
delete collector;
delete importer;
delete context;
delete error_str;
}