Unity使用C++读取文件的方法:
C++侧:
int ReadBytes(const char* szFilePath, size_t& nSize, char*& ppBuff)
{
if (nullptr == szFilePath) return -2;
FILE* fp = NULL;
fp = fopen(szFilePath, "rb");
if (nullptr == fp) return -2;
fseek(fp, 0L, SEEK_END);
nSize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
ppBuff = new char[nSize];
nSize = fread(ppBuff, 1, (size_t)nSize, fp);
if (fp != NULL) {
fclose(fp);
fp = NULL;
}
return 0;
}
C#侧:
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
static extern int ReadBytes(string szFilePath, ref Int32 nSize, ref IntPtr pBuffer);
public static byte[] CSharpReadBytes(string szFilePath)
{
IntPtr pBuffer = IntPtr.Zero;
Int32 nSize = 0;
int nRetCode = ReadBytes(szFilePath, ref nSize, ref pBuffer);
if (nRetCode != 0)
{
if (pBuffer != IntPtr.Zero) {
File_FreeBuffer(pBuffer);
pBuffer = IntPtr.Zero;
}
return null;
}
byte[] buffer = new byte[nSize];
Marshal.Copy(pBuffer, buffer, 0, nSize);
if (pBuffer != IntPtr.Zero)
{
File_FreeBuffer(pBuffer);
pBuffer = IntPtr.Zero;
}
return buffer;
}
这里在使用时如果将CSharpReadBytes函数得到的byte数组传回到c++侧用char*接住,会出现尾部有怪异字符(在使用中时,用的是xml文件,进而会导致解析xml失败)。
为了解决这个问题,可以在初始buffer时,多给一个byte用于传结束符。即:
byte[] buffer = new byte[nSize + 1];
Marshal.Copy(pBuffer, buffer, 0, nSize);
buffer[nSize] = 0;
这样,在C++端解析的时候,能准确识别完整的字符串。这是由于C++的字符串机制决定的,必须有\0结尾。