我假设您的文件包含数组的字节表示。如果是这种情况,那么要模仿仅使用 C++ 的 Objective-C 代码的行为(使这个 C++ 成为唯一的东西是 reinterpret_cast<>,否则它只是直接的 C),您可以使用以下代码。我没有添加任何错误检查,但留下了一些您可能想要执行的 cmets。
float tab[dim1][dim2][dim3];
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef dataTabURL = CFBundleCopyResourceURL(mainBundle, CFSTR("pathOfMyTab"), NULL, NULL);
CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, dataTabURL); // check for NULL return value
CFReadStreamOpen(stream); // check for errors here
CFReadStreamRead(stream, reinterpret_cast<UInt8 *>(tab), sizeof tab); // check that this function returns the number of bytes you were expecting (sizeof tab)
CFReadStreamClose(stream);
// we own "stream" and "dataTabURL" because we obtained these through functions
// with "create" in the name, therefore we must relinquish ownership with CFRelease
CFRelease(stream);
CFRelease(dataTabURL); // ditto
如果您已经在 std::string 中提供了路径,那么您可以使用以下 C++ 代码来模仿您的 Objective-C 代码的行为:
// make sure to include this header
#include <fstream>
// ... then elsewhere in your .cpp file ...
float tab[dim1][dim2][dim3];
std::string path = "path/to/mytab"; // obtain from somewhere
std::ifstream input(path, std::ios::binary); // check that the file was successfully opened
input.read(reinterpret_cast<char *>(tab), sizeof tab); // check that input.gcount() is the number of bytes you expected
我相信在这种情况下我们必须使用reinterpret_cast<>,因为文件包含数组的实际表示(假设它之前以类似的方式写入文件)。
您可以使用混合方法,一旦您拥有包含资源路径的 CFURLRef,您就可以使用 this function 获取 URL 的文件系统表示(提供适当大小的输出缓冲区来存储结果) ,并且从那里您应该能够将其传递给std::ifstream 的构造函数之一(尽管您可能需要转换为适当的类型)。
C++ 不支持变长数组(数组的大小必须在编译时知道)。标准库也没有提供矩阵类型,因此如果表格的尺寸在运行时发生变化,那么您将需要一种完全独立的方法来解决我的答案中的问题。您可以考虑序列化来自 Objective-C 的输出(使用例如 JSON 或其他格式),以便矩阵的维度也写入输出,从而更容易在 C++ 中解析文件。