我有从磁盘读取文件并返回其内容的 Dll:
mydll.h:
extern "C" __declspec(dllexport) void InitFile3dPoints(wchar_t* i_file);
extern "C" __declspec(dllexport) int GetNumPointsForSurface(int i_surf_index);
extern "C" __declspec(dllexport) void GetPointsForSurface
(double* o_result, int i_resultLength, int i_surf_index);
mydll.cpp:
File3dPoints file_3dPoints;
void InitFile3dPoints(wchar_t* i_file)
{ file_3dPoints = readFile3dObjectFromDisk(i_file) }
int GetNumPointsForSurface(int i_surf_index)
{ return file_3dPoints[i_surf_index].getNumPoints(); }
void GetPointsForSurface(double* o_result, int i_resultLength, int i_surf_index);
{
const int num_points = file_3dPoints[i_surf_index].getNumPoints();
if (num_points < i_resultLength)
return;
for (int i = 0; i < num_points; ++i)
o_result[i] = file_3dPoints[i_surf_index].getPoint(i);
}
客户端.cs:
IntPtr inst = LoadLibrary("mydll.dll");
InitFile3dPoints(filename);
for (int i = 0; i < n; ++i)
{
int num_points_for_surface = GetNumPointsForSurface(i);
double[] points = new double[num_points_for_surface];
GetPointsForSurface(points, points.Length, i);
// some code
}
FreeLibrary(inst);
我的 dll 不是线程安全的。一个线程可以调用 InitFile3dPoints。在调用 GetPointsForSurface 之前,另一个线程可以调用 InitFile3dPoints。你能告诉我如何使它成为线程安全的吗?为访问 file_3dPoints 创建互斥锁并不能解决问题,我需要 mydll.cpp 中的每个线程都有其 file_3dPoints 的副本。
谢谢