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

标签 c# c++ file com stream

我在 C# 中有一个包含 xml 数据的内存流对象。

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);

当我将 fileEntity.Bytes 写入 C# 中的文件时,它会正确生成。

但是,我需要使用 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);

但是我在行 fwrite(bytes,1,ub,file) 上遇到异常

Unhandled exception at 0x5f268962 (msvcr100d.dll) in COM.exe: 0xC0000005: Access violation reading location 0x000000001cf1d000.

最佳答案

bytes = (byte*)pSABytes 对于您尝试执行的操作是不合法的。您需要调用 SafeArrayAccessData(pSABytes, &bytes)

关于c# - 在 C# 中将字符串转换为字节数组以在 C++ 中将字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17515045/

相关文章:

c# - 多次处理对象

c++ - 根据 cmake 目标启用宏

c++ - C++ 中的流式 I/O

c++ - 使用自定义比较函数设置构造函数

perl - 取消链接究竟是如何工作的?

java - 在 Java 中将 File[] 转换为 String[]

c# - 异步读同步

c# - MVC : The call is ambiguous between the following methods or properties

c# - 关于 LINQ 查询中透明标识符的句法映射

c++ - 由于符号与 abi::cxx11 的链接问题?