从C ++ Node.js插件渲染文件
我想从C ++插件渲染node.js中的文件。 我想要应用一些文件处理,并通过node.js将输出呈现给浏览器
这是我的C ++代码
std::ifstream in(filename, std::ios::binary); in.seekg (0, in.end); int length = in.tellg(); in.seekg (0, in.beg); char * buffer = new char [length]; in.read (buffer,length); in.close(); return buffer;
以下是为node.js添加绑定的V8代码,这里的缓冲区是上述c ++代码的输出。
Local<Function> cb = Local<Function>::Cast(args[1]); const unsigned argc = 1; Local<Value> argv[argc] = {Local<Value>::New(String::New(buffer))}; cb->Call(Context::GetCurrent()->Global(), argc, argv);
此代码适用于正常的文本文件。 阅读具有Unicode字符的文本文件时遇到问题。 例如,
原始文本文件
test start Billél last
当在节点接收时,我会得到
test start Bill l last
同样,当阅读一个JPG,PNG文件的输出文件是不同于原始文件。 请帮忙。
我也遇到了这个问题。 我在Google的V8例子中find了一个实现。 我发现在这里find正确处理UTF8编码文件的例子:
https://code.google.com/p/v8/source/browse/trunk/samples/shell.cc#218
我改编了这个来源:
const char* ReadFile(const char* fileName, int* fileSize) { // reference to c-string version of file char *fileBuffer = 0; // attempt to open the file FILE* fd = fopen(fileName, "rb"); // clear file size *fileSize = 0; // file was valid if(fd != 0) { // get size of file fseek(fd, 0, SEEK_END); *fileSize = ftell(fd); rewind(fd); // allocate file buffer for file contents fileBuffer = (char*)malloc(*fileSize + 1); fileBuffer[*fileSize] = 0; // copy file contents for (int charCount = 0; charCount < *fileSize;) { int charRead = static_cast<int>(fread(&fileBuffer[charCount], 1, *fileSize - charCount, fd)); charCount += charRead; } // close the file fclose(fd); } return fileBuffer; }
另外,确保在创build一个V8string时创build一个String :: Utf8Value 。
String::Utf8Value v8Utf8String(...);
然后使用String::Utf8Value
作为char*
使用以下函数:
https://code.google.com/p/v8/source/browse/trunk/samples/shell.cc#91