我正在使用 SDL 库在 C++ 中创建游戏。
为了保持所有内容的可读性和有序性,我从实际的游戏程序、菜单程序中制作了一个 dll,并且只有主程序作为可执行文件。在主程序中我创建了一个 struct
它包含所有屏幕信息,例如标准颜色、屏幕的宽度和高度、字体和屏幕的渲染器、窗口和表面对象。在主程序中,我初始化了这个结构的一个实例。指向此实例的指针作为参数传递给 dll 中的函数和对象。
颜色在 std::map<char*, int>
中定义.
要访问颜色,可以使用这样的东西:
struct screen{
std::map<char*, Uint32> colors;
}
screen display;
std::pair<char*, Uint32> color;
color.first = "green";
color.second = 0x00FF00;
display.colors.insert(color);
int x = display.colors["green"] //for example
读取主可执行文件中的值工作正常,但是将屏幕对象作为指向 dll 中函数的指针传递,它返回 NULL
.作为指针,我读取了这样的值:
void function(screen* display){
Uint32 x = display->colors["green"];
}
执行以下操作时:
std::map<char*, int>::iterator i = display->colors.begin();
while(i->first != "green"){
i++
}
int x = i->second;
好像没什么问题。 但我希望能够在 dll 中使用第一种方法,因为第二种方法效率要低得多。
为什么第一种方法在 dll 中不起作用?以及如何让它在 dll 中工作?我使用 visual studio 2012。
最佳答案
我告诉您的指针问题可能是您遇到问题的原因。在可执行文件中,字符串文字 "green"
有一个地址,而在 DLL 中,字符串文字 "green"
有一个完全不同的地址.是的,如果您比较它们,字符串将相等,但指针本身将不相同,从而导致您的问题。
答案就是使用 std::string
作为键。
关于除非使用迭代器,否则 c++ 映射在 dll 中不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434851/