简体   繁体   English

在C#中将字符串转换为字节数组以在C ++中的文件中写入字符串

[英]Convert a string to byte array in C# to write string in a file in C++

I have a Memory stream object in C# containing xml data. 我在C#中有一个包含XML数据的Memory流对象。

fileEntity = new FileEntity();
fileEntity.Bytes = new byte[stream[0].Length];
fileEntity.FileName = ConfigurationManager.AppSettings["BackupPath"].ToString() + "\\" + backupEntity.BackupFileName;

stream.Position = 0;
stream.Read(fileEntity.Bytes, 0, (int)stream[0].Length);

When I write the fileEntity.Bytes to a file in C#, it gets generated correctly. 当我将fileEntity.Bytes写入C#中的文件时,它会正确生成。

However, I need to access bytes in C++ using COM and write the bytes to file. 但是,我需要使用COM访问C ++中的字节并将字节写入文件。

pSABytes = fileentity->GetBytes();
bytes = (byte*)pSABytes;
LONG ub;
HRESULT res = SafeArrayGetUBound(pSABytes, 1, &ub);
FILE* file = fopen("c:\\Abc.xml", "w+");
fwrite( bytes, 1, ub, file );
fclose(file);

However I get an exception on line fwrite(bytes,1,ub,file) 但是我在fwrite(bytes,1,ub,file)行上遇到异常

Unhandled exception at 0x5f268962 (msvcr100d.dll) in COM.exe: 0xC0000005: Access violation reading location 0x000000001cf1d000. COM.exe中0x5f268962(msvcr100d.dll)处未处理的异常:0xC0000005:访问冲突读取位置0x000000001cf1d000。

bytes = (byte*)pSABytes is not legal for what you are trying to do. bytes = (byte*)pSABytes与您尝试执行的操作不合法。 You need to call SafeArrayAccessData(pSABytes, &bytes) 您需要调用SafeArrayAccessData(pSABytes, &bytes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM