我正在为 C++ 模拟框架编写 API。我想在 C# 中使用这个 API。但是我在获取模拟中所有角色的位置时遇到了性能问题。我试图给你一个广泛的解释这个框架是如何工作的。
有一个模拟器类:
class Simulator
{
/// A list of the characters that are currently in the simulation.
std::vector<Character> characters;
/// A list of the path planning results for the characters currently in the simulation.
std::vector<PathPlanningResult*> pathPlanningResults;
/// A mapping from character IDs (which can be set externally) to their positions in the 'characters' and 'PathPlanningResults' lists (which always number from 0).
std::map<int, int> characterVectorPositions;
/** Finds and returns a pointer to the character with the specified ID.
* @param id The ID of the character to find.
* @return A pointer to the Character object that matches the given ID, or NULL if no such character exists.
*/
inline Character* getCharacter(int id)
{
std::map<int,int>::iterator findIt = characterVectorPositions.find(id);
if(findIt == characterVectorPositions.end()) return NULL;
return &characters[findIt->second];
}
/// Adds a character to the simulation, with the specified settings.
bool Simulator::addCharacter(const Point& pos, short layer, const CharacterSettings& settings, int id)
{
Character newCharacter(id, pos, layer, settings);
// add the character
characters.push_back(newCharacter);
// add an empty result
pathPlanningResults.push_back(NULL);
// add the ID mapping
characterVectorPositions.insert(std::pair<int,int>(id, characters.size()-1));
}
}
此类保存模拟中的所有角色对象。
有一个带有获取位置方法的字符类:
class Character
{
/** Returns the current 2D position of the character on its current layer.
* @return The current position of the character.
*/
inline const Point& getPosition() const { return pos; }
}
Point 对象包含 X 和 Y 坐标
还有一个 API 类 API_simulator 有两种获取字符位置的方法:
class API_simulator
{
extern "C" EXPORT_API double GetCharacterX(int charid) {
return simulator->getCharacter(charid)->getPosition().x;
}
extern "C" EXPORT_API double GetCharacterY(int charid) {
return simulator->getCharacter(charid)->getPosition().y;
}
}
当我在 C# 中使用这个 API 时,一切正常。除非我在模拟器中添加了很多角色并且我需要获取所有角色的位置。这需要很长时间,因为每个字符的每个 X 和 Y 坐标都必须在树结构中找到。有没有一种更快的方法来一次获取所有角色的位置?共享内存是解决方案吗?